2

I have a Map of Maps in the format

Map < Integer, Map < String, Integer >>

If I have data in the format of

<1>, << X, 11 >, < Y, 13 >, < Z, 15 >>
<2>, << X,12 >, < A, 23 >, < L, 41 >> 

How to process this using Java 8 lambda and generate the following

<1>, <[11, 13, 15]>
<2>, <[12, 23, 41]> 

That is generate another Map where the key is the key of the outer map and the value is a List of the values of the inner Map. I know how to do this in the regular way but I am looking at how this using Java 8 Lambda.

2
  • Do you mean using Streams with lambdas? If not, what did you do "the regular way" and how do you hope to convert it to lambdas? Commented Jan 27, 2017 at 14:35
  • Java-8 has not only introduce Lambda. Stream and Method Reference can help you to this problem. Commented Jan 27, 2017 at 14:40

1 Answer 1

6

You can use Collectors.toMap to recreate a Map<Integer, List<Integer>> :

input.entrySet().stream()
                .collect(Collectors.toMap(e->e.getKey(),
                                          e->new ArrayList(e.getValue().values())));

In this piece of code, we collect the Entry<Integer, Map<String, Integer>> into a Map<Integer, List<Integer>> by transforming them so that the value becomes the List<Integer> of values of the inner map, while the key stays the same.

You can test it here.

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

1 Comment

Thank you. This is what I was looking for.

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.