How to stream through a Set<Set<Integer>> and put it into a HashMap as the value?

119 Views Asked by At

I have a Set Set:

Set<Set<Integer>> nestedSet = Set.of(Set.of(1, 9), Set.of(0,2,4), Set.of(14,1), Set.of(2,23,13), Set.of(14,22));

What i want to archive, is to stream through the nestedSet in chronology order (i know that a Set is not in chronological order, should i use a LinkedHashSet instead?) and put each of the Sets into the Hashmap as the value. The key of the Hashmap should be a index starting with 0. Something like this:

HashMap<Integer,Set<Integer>> hashMap = new HashMap<>();
for ( int i = 0; i < nestedSet.size; i++){
 nestedSet.stream();
 hashMap.put(i, firstSet);
}

And the output should be:

System.out.printl(hashMap);
{0=[1,9],1=[0,2,4],2=[14,1],3=[2,23,13],4=[14,22]} 
2

There are 2 best solutions below

2
anish sharma On BEST ANSWER

Use like this

    AtomicInteger counter = new AtomicInteger(0);
    Map<Integer,Set<Integer>> map = nestedSet.stream()  .collect(Collectors.toMap(x -> counter.getAndIncrement(), x -> x));

For maintaining insertion order in set you you use linked HashSet

0
peterulb On

Actually you can skip the overhead of the AtomicInteger. Plus easier way to create the LinkedHashSet needed to keep insertion order:

public class App {
    public static void main(String[] args) {
        Set<Set<Integer>> nestedSet = linkedSetOf(linkedSetOf(1, 9), linkedSetOf(0, 2, 4), linkedSetOf(14, 1), linkedSetOf(2, 23, 13), linkedSetOf(14, 22));
        var sharedCounter = new Object() {
            int counter;
        };
        Map<Integer, Set<Integer>> map = nestedSet.stream().collect(Collectors.toMap(num -> sharedCounter.counter++, num -> num));
        System.out.println(map);
    }

    @SafeVarargs
    public static <T> LinkedHashSet<T> linkedSetOf(T... objs) {
        var hashSet = new LinkedHashSet<T>();
        Collections.addAll(hashSet, objs);
        return hashSet;
    }
}