28

I want to order an ArrayList of strings by length, but not just in numeric order.

Say for example, the list contains these words:

cucumber
aeronomical
bacon
tea
telescopic
fantasmagorical

They need to be ordered by their difference in length to a special string, for example:

intelligent

So the final list would look like this (difference in brackets):

aeronomical     (0)
telescopic      (1)
fantasmagorical (3) - give priority to positive differences? doesn't really matter
cucumber        (3)
bacon           (6)
tea             (8)
1

12 Answers 12

30

Use a custom comparator:

public class MyComparator implements java.util.Comparator<String> {

    private int referenceLength;

    public MyComparator(String reference) {
        super();
        this.referenceLength = reference.length();
    }

    public int compare(String s1, String s2) {
        int dist1 = Math.abs(s1.length() - referenceLength);
        int dist2 = Math.abs(s2.length() - referenceLength);

        return dist1 - dist2;
    }
}

Then sort the list using java.util.Collections.sort(List, Comparator).

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

2 Comments

Priority to positive differences can be given by multiplying positive differences by two, and negative differences by negative two, then adding one.
You should make referenceLength final.
17

If you are using java 8 you can also try using this lambda

packages.sort(Comparator.comparingInt(String::length));

Comments

13

If you're using Java 8+ you can use a lambda expression to implement (@Barend's answer as) the comparator

List<String> strings = Arrays.asList(new String[] {"cucumber","aeronomical","bacon","tea","telescopic","fantasmagorical"});
strings.sort((s1, s2) -> Math.abs(s1.length() - "intelligent".length()) - Math.abs(s2.length() - "intelligent".length()));

2 Comments

Best solution for Java 8+. Short and precise.
In case you just want to sort by length: strings.sort((s1, s2) -> s1.length() - s2.length());
5
  • String in Ascending order
class StringLengthListSort implements Comparator<String>{

    @Override
    public int compare(String s1, String s2) {
    return s1.length() - s2.length();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    StringLengthListSort ss = new StringLengthListSort();
    list.add("ram");
    list.add("rahim");
    list.add("ramshyam");
    Collections.sort(list, ss);
    System.out.println(list);
    }

}

Comments

3

You'd do this with the version of Collections.sort() that takes an explicit Comparator.

Comments

3

I have a similar problem solved by lambda expression:

listBeforeSorting.sort((s1, s2) -> s1.length() - s2.length());

This way, we will get sorted-by-length(ascending order) list.

Comments

3
Collections.sort(list, (a, b)->Integer.compare(a.length(), b.length()));

Comments

2

The use of a custom comparator is correct. This is one way to implement it:

    Comparator c = new Comparator<String>()
    {
        public int compare(String s1, String s2) {
            return Integer.compare(s1.length(), s2.length());
        }
    };
    Collections.sort(results, c);
    return results;

Comments

0

simple with Java8 solution with Comparator and Method reference only: Stream.of(list).flatMap(Collection::stream).sorted( Comparator.comparing( String::length)).collect(toList());

Comments

0
The shortest code for this-

public static void main(String... str) {
        List.of("am", "I", "Best", "the").stream().sorted((a, b) -> a.length() - b.length())
                .forEach(System.out::println);
    }

Comments

-1
List<String> list = Arrays.asList("geeksforgeeks", "geeksfor", "geeks");
Collections.sort(list, new Comparator<String>(){
       public int compare(String s1, String s2){
                return s1.length() - s2.length();
       }
});

Comments

-1

Sort the list of string by length using java8

String[] strArr = { "Apples","CSS", "HTML", "Oracle", "Dart"};
    
List<String> result = Arrays.asList(strArr).stream().sorted( (str1,str2) ->  str1.length() - str2.length()).collect(Collectors.toList());
    
System.out.println(result); // output in Ascending Order : [CSS, HTML, Dart, Apples, Oracle]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.