从列表映射java8

时间:2018-05-24 10:22:03

标签: java arraylist java-8 hashmap

我的列表如下:

List<Map<String,Object>> mapList=new ArrayList<>();
Map<String,Object> mapObject=new HashMap<String,Object>();
mapObject.put("No",1);
mapObject.put("Name","test");
mapList.add(mapObject);
Map<String,Object> mapObject1=new HashMap<String,Object>();
mapObject1.put("No",2);
mapObject1.put("Name","test");
mapList.add(mapObject1);

and so on...

现在我希望将键“No”的所有值作为由逗号分隔的字符串,如下所示:

String noList="1,2,3"

任何人都可以建议我做最好的方法。我知道我们可以通过循环来实现它,但不是循环是任何其他方法来实现它。

5 个答案:

答案 0 :(得分:2)

内联说明!

mapList.stream()                       // stream over the list
    .map(m -> m.get("No"))             // try to get the key "No"
    .filter(Objects::nonNull)          // filter any null values in case it wasn't present
    .map(Object::toString)             // call toString for each object
    .collect(Collectors.joining(",")); // join the values

答案 1 :(得分:1)

只需映射列表:

String list = mapList.stream()
    .filter(x -> x.containsKey("No")) // get only the maps that has the key
    .map(x -> x.get("No").toString()) // every map will be transformed like this
   .collect(Collectors.joining(",")); // joins all the elements with ","
System.out.println(list);

使用HashMap<String, Object>表明为此数据创建新类可能更好。你以前考虑过这种可能性吗?

答案 2 :(得分:1)

你可以像这样循环:

List<String> noList = new ArrayList<>(mapList.size());
for (Map<String,Object> m : mapList) {
    Optional.ofNullable(m.get("No")) // get value mapped to "No" or empty Optional
        .map(Object::toString)
        .ifPresent(noList::add); // if not empty, add to list
}
System.out.println(String.join(",", noList));

或内部(官方首选版本IIRC):

List<String> noList = new ArrayList<>(mapList.size());
mapList.forEach(m -> 
    Optional.ofNullable(m.get("No")).map(Object::toString).ifPresent(noList::add));
System.out.println(String.join(",", noList));

现在我想起来了,它比Stream版短。

答案 3 :(得分:0)

30分钟前回答了一个非常类似的问题。

您正在使用重复的键。这使得它看起来像你不需要地图,而是一个具有“No”,“Name”等属性的类。如果你有这个类,你可以在列表上迭代你的实例并连接到一个String。 / p>

如果您想要拥有地图,只需获取“否”键的值,但请注意这是一种错误的做法,您可能应该使用类而不是地图:

String res = "";

for(int i = 0; i < mapList.size(); i++) {
    Map<String,Object> map = mapList.get(i);
    res.concat(map.get("No"));
    if(i != mapList.size() - 1)
        res.concat(",");
}

PS:如果您正在使用不良解决方案,请在其他答案中使用流备选方案,如果您对流的了解足以理解它们。

答案 4 :(得分:0)

试试这个,

String concatValues = mapList.stream().map(map -> String.valueOf(map.get("No")))
        .collect(Collectors.joining(","));
相关问题