按长度排序字符串的ArrayList
我想按长度订购字符串的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 { 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)
对列表进行排序。
如果您使用的是Java 8+,则可以使用lambda表达式来实现(@ Barend的答案)比较器
List 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()));
This will help you - String in Ascending order class StringLengthListSort implements Comparator{ @Override public int compare(String s1, String s2) { return s1.length() - s2.length(); } /** * @param args */ public static void main(String[] args) { List list = new ArrayList (); StringLengthListSort ss = new StringLengthListSort(); list.add("ram"); list.add("rahim"); list.add("ramshyam"); Collections.sort(list, ss); System.out.println(list); } }
您可以使用带有显式Comparator的Collections.sort()版本来完成此操作。
使用自定义比较器是正确的。 这是实现它的一种方法:
Comparator c = new Comparator() { public int compare(String s1, String s2) { return Integer.compare(s1.length(), s2.length()); } }; Collections.sort(results, c); return results;
如果您使用的是Java 8,也可以尝试使用此lambda
packages.sort(Comparator.comparingInt(String::length));
我认为提议的解决方案是非法的。
Comparator接口契约要求比较方法与equals方法一致。
这意味着如果你有x.compareTo(y) == 0
那么你必须有x.equals(y) == true
。
因此,也许这些解决方案在实践中有效,但它们无法保证,并且可能会在下一个版本中出现问题。