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?
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.
You can use groupingBy
instead of toMap
:
Map<String, Set<A>> sysUidToAMap =
mySet.stream()
.collect(Collectors.groupingBy(A::getSystemID,
Collectors.toSet()));
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;
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With