Map<S,S> to List<S>

a 夏天 提交于 2019-12-22 07:36:08

问题


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;

回答1:


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




回答2:


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());


来源:https://stackoverflow.com/questions/30147975/maps-s-to-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!