15

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?

user1386966
  • 3,302
  • 13
  • 43
  • 72

3 Answers3

12

You can use groupingBy instead of toMap:

Map<String, Set<A>> sysUidToAMap =  
    mySet.stream()
         .collect(Collectors.groupingBy(A::getSystemID,
                                        Collectors.toSet()));
Eran
  • 387,369
  • 54
  • 702
  • 768
3

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;
                    }));
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • First, up-vote. what does `0.02$` mean? I have seen you say it several times. – holi-java Jul 20 '17 at 09:10
  • 2
    @holi-java https://en.wikipedia.org/wiki/My_two_cents it sort of mean that this is a very small addition to what has already been said – Eugene Jul 20 '17 at 09:16
  • 1
    And for whatever reason, people like to write `0.02$` instead of `2¢` and sometimes, they even omit the preceding “my”… – Holger Jul 20 '17 at 10:20
2

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));
fps
  • 33,623
  • 8
  • 55
  • 110