按长度差对字符串的 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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
使用自定义比较器:
然后使用 java.util.Collections.sort(List, Comparator) 对列表进行排序。
Use a custom comparator:
Then sort the list using
java.util.Collections.sort(List, Comparator)
.如果你使用 java 8 你也可以尝试使用这个 lambda
If you are using java 8 you can also try using this lambda
如果您使用的是 Java 8+,您可以使用 lambda 表达式来实现(@Barend 的答案为)比较器
If you're using Java 8+ you can use a lambda expression to implement (@Barend's answer as) the comparator
您可以使用 Collections.sort() 接受显式 比较器。
You'd do this with the version of Collections.sort() that takes an explicit Comparator.
我有一个通过 lambda 表达式解决的类似问题:
这样,我们将得到按长度排序(升序)列表。
I have a similar problem solved by lambda expression:
This way, we will get sorted-by-length(ascending order) list.
使用自定义比较器是正确的。这是实现它的一种方法:
The use of a custom comparator is correct. This is one way to implement it:
使用 Java8 解决方案简单,仅包含比较器和方法参考:
Stream.of(list).flatMap(Collection::stream).sorted(Comparator.comparing(String::length)).collect(toList());
simple with Java8 solution with Comparator and Method reference only:
Stream.of(list).flatMap(Collection::stream).sorted( Comparator.comparing( String::length)).collect(toList());
使用java8按长度对字符串列表进行排序
Sort the list of string by length using java8