'Concatenate a String to all elements of a Java stream
I have the following code that parses a Spliterator<Map.Entry> to a Map:
Spliterator<Map.Entry<String, String>> spliterator = ///;
Map<String, String> myMap = (StreamSupport
.stream(spliterator, false)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
I want to change the code such as in my myMap, every key is concatenated with a constant String. Something like that :
Spliterator<Map.Entry<String, String>> spliterator = ///;
String myString = "hello";
String separator = "_";
Map<String, String> myMap = (StreamSupport
.stream(spliterator, false)
.collect(Collectors.toMap(myString+separator+Map.Entry::getKey, Map.Entry::getValue)));
I understand why this is not working but I don't find the good way to do that (without iterating over myMap after the stream). I am not familiar with Streams in Java so I probably missed something obvious.
Solution 1:[1]
You can't use myString+separator+Map.Entry::getKey because Map.Entry::getKey is not a string but a method reference. You should instead use a lambda:
entry -> myString + separator + entry.getKey()
Solution 2:[2]
Use an explicit lambda function instead of a method reference:
.collect(toMap(
e -> myString + separator + e.getKey(),
Map.Entry::getValue
))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Klitos Kyriacou |
| Solution 2 | chrylis -cautiouslyoptimistic- |
