Search code examples
javahashmapsetjava-streamnested-sets

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


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]} 

Solution

  • 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