I'm trying to convert a Map<String, List<String>>
to a Map<String, String>
, where the value for each key is the joint string built by joining all the values in the List
in the previous map, e.g.:
A -> ["foo", "bar", "baz"]
B -> ["one", "two", "three"]
should be converted to
A -> "foo|bar|baz"
B -> "one|two|three"
What's the idiomatic way to do this using the Java 8 Streams API?
In Java, we can use String. join(",", list) to join a List String with commas.
Among those, HashMap is a collection of key-value pairs that maps a unique key to a value. Also, a List holds a sequence of objects of the same type. We can put either simple values or complex objects in these data structures.
Simply use String.join
, no need to create the nested stream:
Map<String, String> result = map.entrySet()
.stream()
.collect(toMap(
e -> e.getKey(),
e -> String.join("|", e.getValue())));
You can use Collectors.joining(delimiter)
for this task.
Map<String, String> result = map.entrySet()
.stream()
.collect(toMap(
Map.Entry::getKey,
e -> e.getValue().stream().collect(joining("|")))
);
In this code, each entry in the map is collected to a new map where:
String
by joining all the elements togetherGoogle Guava has a nice helper method for this:
com.google.common.collect.Maps.transformValues(map, x -> x.stream().collect(joining("|")));
using pure java, this would work:
map.entrySet().stream().collect(toMap(Entry::getKey, e -> e.getValue().stream().collect(joining("|"))));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With