【发布时间】:2019-09-24 18:32:10
【问题描述】:
给定一个这样的排序列表:
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<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();
要获得List<List<Integer>>,您可以使用:
List<List<Integer>> grouped =
new ArrayList<> (a.stream()
.collect(Collectors.groupingBy(Function.identity()))
.values());
第二个 sn-p 生成 List:
[[1, 1, 1], [2], [4], [5, 5], [7]]
【讨论】: