Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 632
user1386966 Avatar asked Jul 20 '17 07:07

user1386966


People also ask

Can we convert Set to map in Java?

identity() is documented at docs.oracle.com/javase/8/docs/api/java/util/function/… It returns a function that accepts one argument and which returns that argument when called. In the collect example the effect is that the values of the stream of entries are taken as is to construct the map.


2 Answers

You can use groupingBy instead of toMap:

Map<String, Set<A>> sysUidToAMap =  
    mySet.stream()
         .collect(Collectors.groupingBy(A::getSystemID,
                                        Collectors.toSet()));
like image 183
Eran Avatar answered Oct 17 '22 16:10

Eran


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;
                    }));
like image 41
Eugene Avatar answered Oct 17 '22 17:10

Eugene