我们可以使用java流的reduce()将map列表转换为Java中的单个map。
请检查以下代码,了解如何使用它。
例如:
@Data
@AllArgsConstructor
public class Employee {
private String employeeId;
private String employeeName;
private Map<String,Object> employeeMap;
}
public class Test{
public static void main(String[] args) {
Map<String, Object> map1 = new HashMap<>();
Map<String, Object> map2 = new HashMap<>();
Map<String, Object> map3 = new HashMap<>();
map1.put("salary", 1000);
Employee e1 = new Employee("e1", "employee1", map1);
map2.put("department", "HR");
Employee e2 = new Employee("e2", "employee2", map2);
map3.put("leave balance", 14);
Employee e3 = new Employee("e3", "employee3", map3);
//now we create a employees list and add the employees e1,e2 and e3.
List<Employee> employeeList = Arrays.asList(e1,e2,e3);
//now we retreive employeeMap from all employee objects and therefore have a List of employee maps.
List<Map<String, Object>> employeeMaps = employeeList
.stream()
.map(Employee::getEmployeeMap)
.collect(Collectors.toList());
System.out.println("List of employee maps: " + employeeMaps);
// to reduce a list of maps to a single map, we use the reduce function of stream.
Map<String, Object> finalMap = employeeMaps
.stream()
.reduce((firstMap, secondMap) -> {
firstMap.putAll(secondMap);
return firstMap;
}).orElse(null);
System.out.println("final Map: "+ finalMap);
}
}
输出:员工地图列表:[{薪水=1000},{部门=HR},{休假余额=14}]。
最终地图:{工资=1000,部门=人力资源,休假余额=14}
PS:对于扩展的答案,很抱歉,这是我第一次使用stackoverflow。谢谢:-)