Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract values (not keys) from a List<Map<String,String>>, and flatten it to a List<String>

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.

like image 614
methuselah Avatar asked Jan 03 '23 07:01

methuselah


2 Answers

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 ());
like image 124
YCF_L Avatar answered Feb 09 '23 22:02

YCF_L


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]
like image 38
Piotr Podraza Avatar answered Feb 10 '23 00:02

Piotr Podraza