Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map<S,S> to List<S>

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;
like image 541
n00b Avatar asked May 10 '15 05:05

n00b


2 Answers

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());
like image 163
Hoopje Avatar answered Sep 27 '22 21:09

Hoopje


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".

like image 45
Bohemian Avatar answered Sep 27 '22 22:09

Bohemian