Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn List<T> into List<Map<K,V>> using Lambda in JAVA8

Tags:

lambda

java-8

I want to get some Objects’ attributes which in a List<Object> and put them into a List<Map<String,Object>> using java8's lambda.In Java7 i would write in this way.To make this readable i want to translate it in another way by Java8's Lambda.

    List<HouseModel> _house = new ArrayList<>();
    List<Map<String, String>> list = new ArrayList<>();
    Map<String, String> map = new HashMap<>(2);
        for (HouseModel h : _house) {
            map.put("address", h.getAddress());
            map.put("number", h.getHouseNum());
            list.add(map);
        }
like image 628
StupidPz Avatar asked Jul 03 '26 20:07

StupidPz


1 Answers

You can map each HouseModel to a Map<String,String> and then collect to a List:

List<Map<String, String>> list =
    _house.stream()
          .map(h -> {Map<String,String> map = new HashMap<>(); 
                     map.put("address", h.getAddress());
                     map.put("number", h.getHouseNum());
                     return map;
                    })
          .collect(Collectors.toList());

Or, if you are using Java 9 and don't mind the created Maps being immutable:

List<Map<String, String>> list =
    _house.stream()
          .map(h -> Map.of("address", h.getAddress(),"number", h.getHouseNum()))
          .collect(Collectors.toList());
like image 53
Eran Avatar answered Jul 06 '26 18:07

Eran