24

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.

9
  • 1
    Create your own comparator. Commented Mar 8, 2016 at 11:33
  • @matt So u mean I can not achieve this through Arrays.sort() Commented Mar 8, 2016 at 11:34
  • 1
    No I mean to use the 2 argument version of Arrays.sort(Object[], Comparator). Commented Mar 8, 2016 at 11:36
  • Arrays.sort() sorted the strings alphabetically. What is the sort criteria you wanted it to use instead? That's the part you will need to write your own comparator for. Commented Mar 8, 2016 at 11:36
  • 2
    Are you sorting by length? This answer may help: stackoverflow.com/questions/8632857/… Commented Mar 8, 2016 at 11:38

10 Answers 10

49

For java 8 and above

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

A more concise way is to use Comparator.comparingInt from Mano's answer here.

Sign up to request clarification or add additional context in comments.

Comments

37

Alternative to and slightly simpler than matt's version

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

3 Comments

This could also open up using more complete comparators. Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder());
How to get it in descending order?
Comparator.comparingInt(String::length).reversed()
19

If you are using JDK 1.8 or above then you could use lambda expression like matt answer. But if you are using JDK 1.7 or earlier version try to write a custom Comparator like this:

String S = "No one could disentangle correctly";
String W[] = S.split(" ");
Arrays.sort(W, new java.util.Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        // TODO: Argument validation (nullity, length)
        return s1.length() - s2.length();// comparision
    }
});

Comments

5

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

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

Comments

1

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

Comments

1

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()));

Comments

1

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]

Comments

0
import java.util.*;

class SortStringArray
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String S = "No one could disentangle correctly";
        String W[] = S.split(" ");
        Arrays.sort(W, new StringLengthComparator());
        for(String str: W)
        System.out.println(str); //print Your Expected Result.
    }
}
 class StringLengthComparator implements Comparator<String>{ //Custom Comparator class according to your need

    @Override
        public int compare(String str1, String str2) {
            return str1.length() - str2.length();// compare length of Strings
        }
 }

Comments

0

//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);

Comments

0
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.