我想按长度顺序排列一个ArrayList字符串,而不仅仅是数字顺序。
例如,该列表包含以下单词:
cucumber
aeronomical
bacon
tea
telescopic
fantasmagorical
需要根据它们的长度差异将它们排序为特殊字符串,例如:
intelligent
因此最终列表如下所示(方括号中的差异):
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)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句