0

I have data that is like this:

List<Map<String, String>> = // psuedocode
[
 {
  "ID": "a",
  "Value": "val1"
 },
 {
  "ID": "b",
  "Value": "val2"
 },
]

I want to turn this to

Map<String, String> = // more pseudocode
{
 "a": "val1",
 "b": "val2"
}

I have something like this so far:

    Map<String, String> output = myList.stream()
            .flatMap(m -> m.entrySet().stream())
            .collect(Collectors.toMap())

Can someone please guide me? The alternative is to use regular for loops, but I am trying to use lambdas.

1
  • 1
    Rather than pseudo-code, it would be helpful if you could come up with a minimal reproducible example. That would stop everyone else having to do the duplicate work of creating a small test. The fact that your code so far doesn't refer to "ID" or "Value" is somewhat surprising... it sounds like you should be mapping each Map<String, String> into a single key-value pair, basically... Commented Jul 15, 2016 at 2:20

2 Answers 2

5

You need to map each Map instance in the list to a key and a value, then collect into a single Map instance.

Map<String, String> output = myList.stream()
  .collect(Collectors.toMap(m -> m.get("ID"), m -> m.get("Value")));

This will throw an exception if an "ID" is duplicated. There are overloaded methods that give you more control over this behavior.

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

Comments

0

while above solution is great, I got the result as follows:

//declared a result map
Map<String, String> result = new ConcurrentHashMap<String, String>();

list.parallelStream().forEach( m -> result.put(m.get("id"), m.get("value")));

You could be safe in concurrent processing situations.

Comments

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.