user1386966
user1386966

Reputation: 3392

How to convert set to map with a set as the value in java 8?

I have the following class:

class A {
   private String id;
   private String name;
   private String systemid;
}

I'm getting a set of A and want to convert it to a map where the key is the system id, and the value is set of A. (Map<String, Set<A>) There can be multiple A instances with the same systemid.

Can't seem to figure out how to do it.. got till here but the identity is clearly not right

Map<String, Set<A>> sysUidToAMap = mySet.stream().collect(Collectors.toMap(A::getSystemID, Function.identity()));

can you please assist?

Upvotes: 15

Views: 18477

Answers (3)

fps
fps

Reputation: 34460

As streams were not specifically requested, here's a way to do it only with the Map API:

Map<String, Set<A>> map = new HashMap<>();
mySet.forEach(a -> map.computeIfAbsent(a.getSystemId(), k -> new HashSet<>()).add(a));

Upvotes: 2

Eugene
Eugene

Reputation: 120858

my 2¢: you can do it with Collectors.toMap but it's slightly more verbose:

      yourSet
      .stream()
            .collect(Collectors.toMap(
                    A::getSystemId,
                    a -> {
                        Set<A> set = new HashSet<>();
                        set.add(a);
                        return set;
                    }, (left, right) -> {
                        left.addAll(right);
                        return left;
                    }));

Upvotes: 3

Eran
Eran

Reputation: 393841

You can use groupingBy instead of toMap:

Map<String, Set<A>> sysUidToAMap =  
    mySet.stream()
         .collect(Collectors.groupingBy(A::getSystemID,
                                        Collectors.toSet()));

Upvotes: 12

Related Questions