按长度对字符串的 ArrayList 进行排序 [英] Sort ArrayList of strings by length
本文介绍了按长度对字符串的 ArrayList 进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想按长度对字符串的 ArrayList 进行排序,而不仅仅是按数字顺序.
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)
推荐答案
使用自定义比较器:
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;
}
}
然后使用 java.util.Collections.sort(List, Comparator)
对列表进行排序.
Then sort the list using java.util.Collections.sort(List, Comparator)
.
这篇关于按长度对字符串的 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文