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

Viewed 115

I have a set let's suppose with 10 unique elements

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

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

I wish to construct a List<Set<String>> such that each element of the list contains a set of size 2.

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

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

How do I implement it using stream in java?

2 Answers

You can use groupingBy with AtomicInteger like this:

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

Note: I used new ArrayList because values() return Collection and not List as you expect. Also if you want to got another size, you can change only 2.

response:

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

This solution is very similar to YCF_L's solution but uses Collectors.collectingAndThen to handle the conversion of Collection to ArrayList.

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())));

Related