The question is to print the array of string in accordance with the length of strings in ascending order.
For example
input={"vellore","i","from","am"}
output=i am from vellore
Here is my code:
int n=sc.nextInt();
sc.nextLine();
String[] arr = new String[n];
for(int i=0;i<n;i ){
arr[i]=sc.nextLine();
}
//System.out.println(Arrays.toString(arr));
Arrays.sort(arr);
for(String i: arr){
System.out.print(i " ");
}
Now I know that my output will come in lexical order that is as "am from i vellore", but I want to get my desired output using sort method. I tried using Collections.sort() as well by using arraylist but I still didn't get my desired output.
I want to get my output using sort method without using the normal approach by comparing the lengths of string and all.
CodePudding user response:
You want a Comparator. In this case, you specifically want to start by comparing the String lengths. I would suggest you then compare naturally (to break ties). Like,
String[] arr = { "vellore", "i", "from", "am" };
Arrays.sort(arr, Comparator.comparingInt(String::length)
.thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(arr));
Outputs (as requested)
[i, am, from, vellore]
CodePudding user response:
tl;dr
Comparator
.comparingLong( ( String s ) -> s.codePoints().count() )
.thenComparing( Comparator.naturalOrder() )
Avoid legacy type char
The Answer by Frisch is correct in suggesting the use of a Comparator. However, the method reference seen there, String::length, fails with most characters. See this example. The String#length method reports a two-character string like c
