Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting string lengths using comparator

Tags:

java

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.

like image 553
JohnJ Avatar asked Dec 26 '11 04:12

JohnJ


2 Answers

One Liners

Ascending

Arrays.sort(words, Comparator.comparingInt(String::length));

Descending

Arrays.sort(words, Comparator.comparingInt(String::length).reversed());
like image 61
Dhruvan Ganesh Avatar answered Sep 20 '22 21:09

Dhruvan Ganesh


Achieved same by using stream and comparator as below-

Arrays.stream(array)
      .sorted(Comparator.comparingInt(String::length))
      .forEach(a -> System.out.print(a + " "));
like image 31
Harshank Avatar answered Sep 16 '22 21:09

Harshank