Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从一组贴图创建特定值列表的有效方法_Java_List_Dictionary_Java 8_Java Stream - Fatal编程技术网

Java 从一组贴图创建特定值列表的有效方法

Java 从一组贴图创建特定值列表的有效方法,java,list,dictionary,java-8,java-stream,Java,List,Dictionary,Java 8,Java Stream,假设我有一张地图列表 List<Map<String, Double>> maps = new ArrayList<>(); Map<String, Double> map1 = new HashMap(); map1.put("height",60D); map1.put("weight",144D); maps.add(map1); Map<String, Double> map2 = new HashMap(); map2

假设我有一张地图列表

List<Map<String, Double>> maps = new ArrayList<>();

Map<String, Double> map1 = new HashMap();
map1.put("height",60D);
map1.put("weight",144D);

maps.add(map1);


Map<String, Double> map2 = new HashMap();
map2.put("height",63D);
map2.put("weight",192D);

maps.add(map2);
List maps=new ArrayList();
Map map1=新的HashMap();
图1.put(“高度”,60D);
图1.放置(“重量”,144D);
添加(map1);
Map map2=新的HashMap();
图2.put(“高度”,63D);
地图2.放置(“重量”,192D);
添加(map2);
等等

创建高度或重量列表的最快方法是什么? 比如列表高度等等

经典的方法是查看地图,使用if条件并搜索高度键,然后如果找到,将其添加到返回列表中

使用streams的等效方法是什么?

List listHeights=maps.stream()
List<Double> listHeights = maps.stream()
                                .map(map -> map.get("height"))
                                .filter(Objects::nonNull)
                                .collect(Collectors.toList());
.map(map->map.get(“高度”)) .filter(对象::非空) .collect(Collectors.toList());

类似地,您也可以对
weight
执行此操作。

您可以在列表上进行流式处理,并将映射映射到相关值:

List<Double> heights =
    maps.stream()
        .filter(m -> m.containsKey("height"))
        .map(m -> m.get("height"))
        .collect(Collectors.toList());
列表高度=
maps.stream()
.filter(m->m.containsKey(“高度”))
.map(m->m.get(“高度”))
.collect(Collectors.toList());

如果您想一次获得
高度和
重量列表,请使用
收集器。groupingBy
无需
包含
检查

Map<String, List<Double>> result = maps.stream()
                                           .flatMap(m->m.entrySet().stream())
                                           .collect(Collectors.groupingBy(Map.Entry::getKey,
                                                   Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

    result.forEach((k,v)->System.out.println(k+"..."+v));
您还可以使用
getOrDefault
获取身高或体重的
列表

List<Double> height = result.getOrDefault("height", new ArrayList<Double>());
List height=result.getOrDefault(“height”,new ArrayList());

并且它不应该编译,您有一个
列表
,但是在
过滤器
映射
周围添加了
映射
新缺少的结束括号
。。。而
containsKey
将是
过滤器中更好的选择,如果映射不包含键,则
filter
null
添加到结果列表中
List<Double> height = result.getOrDefault("height", new ArrayList<Double>());