Reputation: 11136
Say I have a List of maps
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);
and so on...
What's the quickest way to create a list of heights or weights? Something like List heights etc.
The classic way is to look through the map, use an if condition and search for a height key and then if found, add it to a return list.
What would the equivalent way to do it using streams?
Upvotes: 0
Views: 85
Reputation: 16053
List<Double> listHeights = maps.stream()
.map(map -> map.get("height"))
.filter(Objects::nonNull)
.collect(Collectors.toList());
Similarly, you can do it for weight
also.
Upvotes: 7
Reputation: 40078
If you wanna get both height
and weight
list in one shot, then use Collectors.groupingBy
no need of contains
or null
check
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));
Output
weight...[144.0, 192.0]
height...[60.0, 63.0]
And also you can use getOrDefault
to get the List
of height or weight
List<Double> height = result.getOrDefault("height", new ArrayList<Double>());
Upvotes: 1
Reputation: 311808
You could stream over the list and map the Maps to the relevant values:
List<Double> heights =
maps.stream()
.filter(m -> m.containsKey("height"))
.map(m -> m.get("height"))
.collect(Collectors.toList());
Upvotes: 2