How to sort String array by length using Arrays.sort()

Viewed 49932

I am trying to sort an array of strings according to their length using Arrays.sort(), but this sorts the strings lexicographically rather than by length. Here is my code:

S = "No one could disentangle correctly"
String W[] = S.split(" ");
Arrays.sort(W);

After sorting :

correctly
could
disentangle
no
one

but what I want is

no  //length = 2
one //length = 3
could //length = 4 and likewise
correctly
disentangle

How can I get the above output? Please give answer for JDK 1.7 & JDK1.8.

10 Answers

Simply changing the parameter position we can sort in descending order.

Arrays.sort(W, (a,b)->b.length() - a.length());

Java 8 is pretty easy. as mentioned in the above answer. I was solving some problems on hackerrank and there they are using java 7. so I had to write the java7. That is selection sort. though time complexity is not great O(n^2) however it serves the purpose.

public static void main(String[] args) {
    // I am taking list and again converting to array. please ignore. you can directly take array of          string and apply the logic.
        List<String> listOfString = new ArrayList<String>();
        listOfString.add("because");
        listOfString.add("can");
        listOfString.add("do");
        listOfString.add("must");
        listOfString.add("we");
        listOfString.add("what");
        String[] w= new String[listOfString.size()];

        for(int i =0;i <listOfString.size();i++) {
            w[i] = listOfString.get(i);
        }
        // That is for java 8
        //Arrays.sort(w, (a, b)->Integer.compare(a.length(), b.length()));

        for (int i = 0; i < w.length; i++) {
                for(int j=i+1;j<w.length;j++) {
                    String tempi = w[i];
                    String tempj = w[j];

                    if(tempj.length()<tempi.length()) {
                        w[i] =w[j];
                        w[j]=tempi;
                    }
                }
        }

       // That is for printing the sorted array
        for (int i = 0; i < w.length; i++) {
            System.out.println(w[i]);
        }

Output.

do
we
can
must
what
because

If you prefer Streams in Java8 onwards then you could use -

String input = "This is a beautiful world";
String[] arr = Arrays.stream(input.split(" "))
                     .sorted(Comparator.comparingInt(String::length))
                     .toArray(String[]::new);
// prints output
System.out.println(Arrays.toString(arr));

The output is -

[a, is, This, world, beautiful]

My answer is kind of irrelevant to this question (I wanted to sort and a list not an array) but since the answers provided here helped me solve my error, am going to leave it here for those that are facing the issue had.

Collections.sort(vehicles, (VehiclePayload vp1, VehiclePayload vp2) 
    -> Integer.compare(vp2.getPlateNumber().length(), vp1.getPlateNumber().length()));

//possible but not recommended;

 String sp[]="No one could disentangle correctly".split(" ");
    
    for(int i=0;i<sp.length-1;i++)
    {
        for(int j=i+1;j<sp.length;j++)
        {
            if(sp[i].length()>sp[j].length())
            {
                String temp=sp[i];
                sp[i]=sp[j];
                sp[j]=temp;
            }
        }
    }
    for(String i:sp) //will print content of array sp
        System.out.println(i);
ArrayList<String> list=new ArrayList<>();
    list.add("diamond");
    list.add("silver");
    list.add("gold");
    
    System.out.println(list.stream().sorted(Comparator.comparingInt(String::length)).collect(Collectors.toList()));

output:

[gold, silver, diamond]
Related