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 speci开发者_运维技巧al 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)
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)
.
If you are using java 8 you can also try using this lambda
packages.sort(Comparator.comparingInt(String::length));
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()));
- 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);
}
}
You'd do this with the version of Collections.sort() that takes an explicit Comparator.
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.
Collections.sort(list, (a, b)->Integer.compare(a.length(), b.length()));
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;
simple with Java8 solution with Comparator and Method reference only: Stream.of(list).flatMap(Collection::stream).sorted( Comparator.comparing( String::length)).collect(toList());
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);
}
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();
}
});
if you are using Kotlin you can use this code
var A = ArrayList<String>()
A.add("Alen")
A.add("Nymar")
A.add("Ronaldo")
A.add("Totianas")
A.add("Ted")
A.add("Sara")
Collections.sort(A, object : Comparator<String?> {
override fun compare(p0: String?, p1: String?): Int {
return (p1!!.length - p0!!.length)
}
})
System.out.println(A)
精彩评论