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);
}
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());
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