0

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 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your fast reply. Is there an easy and fast way to insert subsets to the LinkedHashSet as i did in The nested set. Something similar to Set.of(1,2,3)? I dont want to do linkedHashSet.add 20 times
I don't think so there is any short for that operation
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.