[英]Sort ArrayList of strings by length
I want to order an ArrayList of strings by length, but not just in numeric order.我想按长度排序字符串的 ArrayList,但不仅仅是按数字顺序排序。
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)
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)
.然后使用
java.util.Collections.sort(List, Comparator)
对列表进行排序。
If you're using Java 8+ you can use a lambda expression to implement (@Barend's answer as) the comparator如果您使用的是 Java 8+,则可以使用 lambda 表达式来实现(@Barend 的答案为)比较器
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()));
如果你使用的是 java 8 你也可以尝试使用这个 lambda
packages.sort(Comparator.comparingInt(String::length));
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);
}
}
您可以使用带有显式Comparator的Collections.sort()版本来执行此操作。
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;
I have a similar problem solved by lambda expression:我有一个由 lambda 表达式解决的类似问题:
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()));
简单的 Java8 解决方案,只有比较器和方法参考: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如果您使用的是Kotlin ,则可以使用此代码
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)
I think the proposed solutions are illegal. 我认为提议的解决方案是非法的。
The Comparator interface contract demands that the comparison method be consistent with the equals method. Comparator接口契约要求比较方法与equals方法一致。
That means if you have x.compareTo(y) == 0
then you must have x.equals(y) == true
. 这意味着如果你有
x.compareTo(y) == 0
那么你必须有x.equals(y) == true
。
So, maybe the solutions work in practice, but they are not guaranteed to, and may break in the next release. 因此,也许这些解决方案在实践中有效,但它们无法保证,并且可能会在下一个版本中破解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.