How to convert List<Map> to List<String> in java streams


Convert List<Map<String,String>> to List<String> by taking values from map as output list.

  1. To convert List<Map> to List<String> we need to map Map to List by taking value set or Keyset, after that need to flat map the result.
List result = list.stream().map(map->new ArrayList<String>(map.values())).
                                      flatMap(List::stream).collect(Collectors.toList());

Example


import java.util.Date;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class HelloWorld {
    public static void main(String[] args) {
        Map<String,String> map1 = new HashMap<>();
        map1.put("one", "Apple");
        map1.put("two", "Orange");
        Map<String,String> map2 = new HashMap<>();
        map2.put("three", "Cat");
        map2.put("four", "Dog");
        Map<String,String> map3 = new HashMap<>();
        map3.put("five", "Cricket");
        map3.put("six", "Football");
        List<Map<String, String>> list = new ArrayList<>();
        list.add(map1);
        list.add(map2);
        list.add(map3);
        List result = list.stream().map(map->new ArrayList<String>(map.values())).
                                      flatMap(List::stream).collect(Collectors.toList());
        System.out.println(result);
    }
    
}

Output :

[Apple, Orange, Dog, Cat, Football, Cricket]