Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining a List<String> inside a map

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?

like image 422
Raibaz Avatar asked Nov 10 '15 11:11

Raibaz


People also ask

How do you join a List into a string in Java?

In Java, we can use String. join(",", list) to join a List String with commas.

Can you put a List in a HashMap?

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.


3 Answers

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())));
like image 185
Tagir Valeev Avatar answered Oct 02 '22 04:10

Tagir Valeev


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:

  • the key stays the same
  • the value, which is a list, is collected to a String by joining all the elements together
like image 32
Tunaki Avatar answered Oct 02 '22 02:10

Tunaki


Google 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("|"))));
like image 20
muued Avatar answered Oct 02 '22 03:10

muued