使用 stream() 在特定条件下将 Set<String> 转换为 List<Set<String>>

Converting a Set<String> to List<Set<String>> with specific conditions using stream()

我有一个集合,假设有 10 个独特的元素

Set<String> myset =new HashSet<String>();

[a,b,c,d,e,f,g,h,i,j]

我希望构建一个 List<Set<String>> 列表中的每个元素都包含一组大小为 2 的元素。

List<Set<String>> myList = new ArrayList<Set<String>>();

[
[a,b],
[c,d],
[e,f],
[g,h],
[i,j]
]

如何使用 java 中的 stream 实现它?

您可以像这样将 groupingByAtomicInteger 一起使用:

AtomicInteger ai = new AtomicInteger();
List<Set<String>> myList = new ArrayList<>(
        myset.stream()
                .collect(Collectors.groupingBy(
                        s -> ai.getAndIncrement() / 2, 
                        Collectors.toSet()))
                .values());

注意:我使用 new ArrayList 是因为 values() return Collection 而不是您期望的 List。另外如果你想要其他尺寸,你可以只更改 2.

回复:

[[a, b], [c, d], [e, f], [g, h], [i, j]]

此解决方案与 YCF_L 的解决方案非常相似,但使用 Collectors.collectingAndThen 来处理 CollectionArrayList 的转换。

Collector<String,?,Map<Integer, Set<String>>> grpBy =
    Collectors.groupingBy(s -> ai.getAndIncrement() / 2,
                          Collectors.toSet());

return mySet.stream()
            .collect(collectingAndThen(grpBy,
                                       map -> new ArrayList<>(map.values())));