Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert a Map<String, List<String>> to Map<String, String> in java 8

I have a map like

key= ["a1", "a2", "a3"] 
value = [["a1.value1", "a1.value2"],["a2.value1", "a2.value2"]]

the resulting Map should be like

key = ["a1", "a2", "a3"]
value = ["a1.value1, a1.value2", "a2.value1, a2.value2"]

How can we use Collectors.joining as an intermediate step ?

like image 977
stackaccount Avatar asked Nov 17 '18 22:11

stackaccount


People also ask

How do I convert a Map to a String in Java?

Use Object#toString() . String string = map. toString();

How do I convert a List to a String in Java?

We can use StringBuilder class to convert List to String. StringBuilder is the best approach if you have other than String Array, List. We can add elements in the object of StringBuilder using the append() method while looping and then convert it into string using toString() method of String class at the end.

Can we convert List to Map in Java?

With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.


1 Answers

How can we use Collectors.joining as an intermediate step ?

You mean, in the collecting phase...

Yes, you can:

Map<String, String> result = 
        source.entrySet()
              .stream()
              .collect(toMap(Map.Entry::getKey, 
                      e -> e.getValue().stream().collect(joining(", "))));

but, better to use String.join:

Map<String, String> result = 
     source.entrySet()
           .stream()
           .collect(toMap(Map.Entry::getKey, e -> String.join(", ", e.getValue())));

or none stream variant:

Map<String, String> resultSet = new HashMap<>();
source.forEach((k, v) -> resultSet.put(k, String.join(",", v)));
like image 149
Ousmane D. Avatar answered Oct 17 '22 19:10

Ousmane D.