While trying to sort an array based on its element string lengths, I am struck with a compile error. I have an set to start with, ,
Set<String> arraycat = new HashSet<String>();
//add contents to arraycat
String[] array = arraycat.toArray(new String[0]);
//array looks like this now:
//array=[cat,cataaaa,cataa,cata,cataaa]
I would ideally want to sorted to
array=[cat,cata,cataa,cataaa,cataaaa]
so I have a comparator of type
class comp implements Comparator {
public int compare(String o1, String o2) {
if (o1.length() > o2.length()) {
return 1;
} else if (o1.length() < o2.length()) {
return -1;
} else {
return 0;
}
}
}
and then I call the class by
Collections.sort(array, new comp());
but then, it throws me two compile errors:
comp is not abstract and does not override abstract method compare(java.lang.Object,java.lang.Object) in java.util.Comparator
class comp implements Comparator {
^
testa.java:59: cannot find symbol
symbol : method sort(java.lang.String[],comp)
location: class java.util.Collections
Collections.sort(array, new comp());
^2 errors
I would appreciate any clues to solve the problem.
One Liners
Ascending
Arrays.sort(words, Comparator.comparingInt(String::length));
Descending
Arrays.sort(words, Comparator.comparingInt(String::length).reversed());
Achieved same by using stream and comparator as below-
Arrays.stream(array)
.sorted(Comparator.comparingInt(String::length))
.forEach(a -> System.out.print(a + " "));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With