Search code examples
javajava-stream

Return Map with (unique) key and collection of values that match the same


I have a simple object:

Value { a: int, 
        b: string, 
        c: boolean, ... 
        some other fields/members }

The key identifier is generated from the values of a, b, and c${a}${b}${c}__${someOtherStringValue}.

I'm receiving a set of Value and I would like (ideally) to use the Stream API to output a map with key identifier as key, and the corresponding collection of Value objects that matches the key as value: Map<String, Collection<Value>>.

This is what I have so far, but it doesn't quite work yet...

final var values = Set.of(v1, v2, v3, ..., vN);
final Map<String, Collection<Value>> results = values.stream()
  .map(it -> keyIdentifierFrom(it, someOtherStringValue))
  .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

Anyone with streaming super-powers can help?


Solution

  • I think this should work

    final var values = Set.of(v1, v2, v3, ..., vN);
    final Map<String, List<Value>> results = values.stream()
      .collect(Collectors.groupingBy(it -> keyIdentifierFrom(it, someOtherStringValue)));