Note that you only create one authentication object: new HashSet<MyEnum>() .
BinaryOperator that you supply as the third argument should be idempotent , just like normal math operators, for example. x = y + z does not change the values โโof y and z .
This means that you need to combine the two input sets a and b without updating them.
In addition, when working with enumerations, you should use EnumSet , not HashSet .
Map<MyKey, Set<MyEnum>> map = myObjs.stream() .collect(Collectors.groupingBy( MyType::getMyKey, Collectors.reducing( EnumSet.noneOf(MyEnum.class), // <-- EnumSet MyType::getMyEnums, (a, b) -> { EnumSet<MyEnum> c = EnumSet.copyOf(a); // <-- copy c.addAll(b); return c; })));
UPDATE
A shorter, more optimized version that should not create new sets when accumulating the result:
Map<MyKey, Set<MyEnum>> map = myObjs.stream() .collect(Collectors.groupingBy( MyType::getMyKey, Collector.of( () -> EnumSet.noneOf(MyEnum.class), (r, myObj) -> r.addAll(myObj.getMyEnums()), (r1, r2) -> { r1.addAll(r2); return r1; } )));
source share