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 ?
Use Object#toString() . String string = map. toString();
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.
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.
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)));
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