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