问题描述:有一个用户列表List<User>,须将每个User部分字段提取出来,重新放入一个Map中,然后将生成的Map放入List中。
原来代码片段如下:
public static List<Map<String, Object>> toListMap(List<User> userList) {
List<Map<String, Object>> result = new ArrayList<>();
Map<String, Object> map;
for (User user : userList) {
map = new HashMap<>();
map.put("username", user.getUsername());
map.put("age", user.getAge());
map.put("gender", user.getGender());
result.add(map);
}
return result;
}
使用Java 8 stream后,用map做转换,参考代码片段如下:
方法一:
private Map<String, Object> toMap(User user) {
Map<String, Object> map = new HashMap<>();
map.put("username", user.getUsername());
map.put("age", user.getAge());
map.put("gender", user.getGender());
return map;
}
List<Map<String, Object>> data = userList.stream()
.map(this::toMap)
.collect(Collectors.toList());
方法二(一步到位)
List<Map<String, Object>> data = userList.stream().map(user -> {
Map<String, Object> map = new HashMap<>();
map.put("username", user.getUsername());
map.put("age", user.getAge());
map.put("gender", user.getGender());
return map;
}).collect(Collectors.toList());