Zohra Khan
Zohra Khan

Reputation: 5302

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

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.

Upvotes: 24

Views: 69390

Answers (10)

Baba Fakruddin
Baba Fakruddin

Reputation: 189

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]

Upvotes: 0

shailendra1118
shailendra1118

Reputation: 71

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]

Upvotes: 1

Arif Shaik
Arif Shaik

Reputation: 1

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

Upvotes: 0

Kasasira
Kasasira

Reputation: 403

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

Upvotes: 1

matt
matt

Reputation: 12347

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.

Upvotes: 49

Varun
Varun

Reputation: 4452

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

Upvotes: 1

Abhijeet Gupta
Abhijeet Gupta

Reputation: 51

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

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

Upvotes: 5

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

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
        }
 }

Upvotes: 0

mmuzahid
mmuzahid

Reputation: 2270

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

Upvotes: 19

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22224

Alternative to and slightly simpler than matt's version

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

Upvotes: 37

Related Questions