给定这样的排序列表:
List<Integer> a = Arrays.asList(1, 1, 1, 2, 4, 5, 5, 7);
是否有单行方式将此数组拆分为子列表,每个子列表包含相等值的元素,例如:
List[List[1, 1, 1], List[2], List[4], List[5, 5], List[7]]
您可以流式传输的元素,List并用于Collectors.groupingBy()对相同的元素进行分组。它将产生一个Map<Integer,List<Integer>>,您可以获得values() Collection:
Collection<List<Integer>> grouped =
a.stream()
.collect(Collectors.groupingBy(Function.identity()))
.values();
Run Code Online (Sandbox Code Playgroud)
要获得,List<List<Integer>>您可以使用:
List<List<Integer>> grouped =
new ArrayList<> (a.stream()
.collect(Collectors.groupingBy(Function.identity()))
.values());
Run Code Online (Sandbox Code Playgroud)
第二个片段产生List:
[[1, 1, 1], [2], [4], [5, 5], [7]]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33 次 |
| 最近记录: |