我有一个包含字符串的ArrayList例如列表1可能是名称列表:
比尔,比尔,比尔,亨利,苏,苏
我如何使用Java流按排序顺序(按出现顺序)按如下方式返回数组?
Bill,Bill,Bill,Sue,Sue,Henry
知道如何显示的最终排名也很棒
比尔,苏,亨利.我有以下代码:
System.out.println(
name.stream()
.sorted(Comparator.comparing(a->a))
.collect(Collectors.toList())
);
name是数组.
它工作正常,并根据名称排列数组,但我也想介绍排名.
解决方法:
首先,不清楚您实际想要实现什么:List< List< String>>或List< String []>或String [] …
您一方面想要Bill,Bill,Bill,Sue,Sue,Henry,但如果您的清单是{Bill,Bill,Bill,Sue,Henry,Henry}; {Bill,Gene,Sue}在这种情况下,您的结果是什么?单个String []或….究竟是什么?您还提到了如何显示Bill,Sue,Henry的最终排名,这显然完全意味着其他…
任何状况之下:
Shmosel在评论中的解决方案确实非常好! (但假设有两件事,您的列表是可编辑的,因此您可以对其进行排序,并且希望使用排序后的List而不是数组).而且,您不能将其重构为返回数组的单个流操作,因为那将意味着两次消耗流…这是您无法做到的.
您可以通过两个操作来做到这一点:
List flat = all.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
String[] result = flat.stream()
.sorted(Comparator.comparing(x -> Collections.frequency(flat, x)).reversed())
.toArray(String[]::new);
我上面给出的输入将是:
[Bill, Bill, Bill, Bill, Henry, Henry, Sue, Sue, Gene]
如果要对每个列表进行排序,则可以使用:
List> res = all.stream()
.map(x -> x.stream()
.sorted(Comparator.comparing(y -> Collections.frequency(x, y)).reversed())
.collect(Collectors.toList()))
.collect(Collectors.toList());
结果将是:
[[Bill, Bill, Bill, Henry, Henry, Sue], [Bill, Gene, Sue]]
标签:java-stream,java
来源: https://codeday.me/bug/20191108/2009706.html