5

How do I convert a List<Entry> to Map<Entry::getKey, List<Entry::getValue>> using streams in Java 8?

I couldn't come up with a good KeySelector for Collectors.toMap():

List<Entry<Integer, String>> list = Arrays.asList(Entry.newEntry(1, "a"), Entry.newEntry(2, "b"), Entry.newEntry(1, "c"));
        Map<Integer, List<String>> map = list.stream().collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

What I want to get: {'1': ["a", "c"], '2': ["b"]}.

3
  • Are you sure you don't have any duplicate keys in your entry List? Commented Jun 8, 2018 at 14:25
  • @TrippKinetics there are two entries which have their keys as 1 Commented Jun 8, 2018 at 14:28
  • @Aominè That appears to be one entry with the key of 1 and the value of ["a", "c"]. What I'm talking about would be something like {'1': ["a", "c"], '1': ["x", "z"] ... } Commented Jun 8, 2018 at 14:35

1 Answer 1

10

You can do so by using the groupingBy collector along with mapping as the downstream collector:

myList.stream()
       .collect(groupingBy(e -> e.getKey(), mapping(e -> e.getValue(), toList())));

import required:

import static java.util.stream.Collectors.*;

You can actually accomplish the same result with the toMap collector:

 myList.stream()
       .collect(toMap(e -> e.getKey(), 
                 v -> new ArrayList<>(Collections.singletonList(v.getValue())),
              (left, right) -> {left.addAll(right); return left;}));

but it's not ideal when you can use the groupingBy collector and it's less readable IMO.

Sign up to request clarification or add additional context in comments.

2 Comments

How can I avoid static import? There's an error about lambdas if I write .collect( Collectors.groupingBy(e -> e.getKey(), Collectors.mapping(e -> e.getValue(), Collectors.toList()))); )
IDEA loses the type of e, it says it's just an Object. Actually fixed it by retyping somehow, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.