How would I extract the values (not keys) from a List<Map<String,String>>
, and flatten it to a List<String>
?
i.e. tried the following but doesn't work.
List<Map<String,String>> mapList = .... ;
List<String> valueList = mapList.stream()
.map(o -> o.getValue())
.collect(Collectors.toList());
I'd like to filter the result by a given key as well.
You mean :
List<String> valueList = mapList.stream()
.flatMap(a -> a.values().stream())
.collect(Collectors.toList());
Edit
What if I want to specify a key e.g. I have "id" and "firstName", but only want "firstName"
In this case you can use filter
after the flatmap
like so :
List<String> valueList = mapList.stream()
.flatMap(a -> a.entrySet().stream())
.filter (e -> e.getKey().equals("firstName"))
.map(Map.Entry::getValue)
.collect(Collectors.toList ());
Use .flatMap
:
List<Map<String,String>> mapList = new ArrayList<>();
Map<String, String> mapOne = new HashMap<>();
mapOne.put("1", "one");
mapOne.put("2", "two");
Map<String, String> mapTwo = new HashMap<>();
mapTwo.put("3", "three");
mapTwo.put("4", "four");
mapList.add(mapOne);
mapList.add(mapTwo);
List<String> allValues = mapList.stream()
.flatMap(m -> m.values().stream())
.collect(Collectors.toList()); // [one, two, three, four]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With