Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort ArrayList of strings by length

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)
like image 685
Matt Avatar asked Sep 27 '11 21:09

Matt


People also ask

How do you sort an array of strings based on length?

To sort the array by its string length, we can use the Array. sort() method by passing compare function as an argument. If the compare function return value is a. length - b.

How do you sort elements in an ArrayList?

In order to sort elements in an ArrayList in Java, we use the Collections. sort() method in Java. This method sorts the elements available in the particular list of the Collection class in ascending order. where list is an object on which sorting needs to be performed.


3 Answers

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).

like image 91
Barend Avatar answered Dec 17 '22 11:12

Barend


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

packages.sort(Comparator.comparingInt(String::length)); 
like image 34
SamHoque Avatar answered Dec 17 '22 09:12

SamHoque


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()));
like image 29
Josh Johnson Avatar answered Dec 17 '22 10:12

Josh Johnson