I'm trying to convert a Map<String, String>
to a List<String>
using lambdas.
Essentially I'd like to concatenate the key and value with an '='
in between. This seems trivial but I can't find how to do it.
E.g.
Map<String, String> map = new HashMap<>();
map.put("a1","b1");
map.put("a2","b2");
map.put("a3","b3");
// Lambda
// Result contains ["a1=b1", "a2=b2", "a3=b3"]
List<String> result;
First of all, if the requirement is just using a Lambda, you can just put your normal code into a function and call it:
Function<Map<S,S>,List<S>> function = (Map<S,S> map) -> {
// conventional Java code
return result;
};
List<S> list = function.apply(inputMap);
Probably what you meant is that you want to use Java 8's stream library. A stream always consists of a stream source, then some intermediate operations, and finally a final operation which constructs the result of the calculation.
In your case, the stream source is the entry set of the map, the intermediate operation converts each entry to a string, and finally the final operation collects these string into a list.
List<S> list =
map.entrySet().stream()
.map(e -> e.getKey().toString() +
"=" + e.getValue().toString())
.collect(Collectors.toList());
For java 7, you can do it in one line too, starting from Map#toString()
:
List<String> list = Arrays.asList(map.toString().replaceAll("^.|.$", "").split(", "));
But it is vulnerable to keys/values containing commas.
In java 8, use Map.Entry#toString()
over the entry stream:
List<String> list = map.entrySet().stream().map(Object::toString).collect(Collectors.toList());
which isn't vulnerable to commas.
Both solutions use the fact that Map.Entry#toString()
returns "key=value".
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