有没有办法使用流或其他方式从 Java 8 中的列表创建多个 map ?
我有一个自定义对象列表。 假设列表中的 Employee 具有departmentId,因此有一些员工具有相同的departmentId =“001”。 我想根据 Employee.departmentId 创建多个 map 。
例如,
map1 = <“001”,员工1>,<“001”,员工3>,<“001”,员工8>...<“001”,员工100>
map2 = <“002”,员工2>,<“002”,员工4>,...,<“002”,员工8> ... 像这样的东西。
因为对于列表中的每个元素,检查departmentId 并使用旧的for 循环将其放入相应的映射中。想知道是否有更好的方法来做到这一点?目前我正在使用 Java 8
最佳答案
正如建议的那样,使用 Map<String,List<Employee>>
可能就是你想要的。我构建了一个小类和一个示例来说明该过程。
List<Employee> emps = List.of(
new Employee("001", "Jim"),
new Employee("002", "Bob"),
new Employee("001", "June"),
new Employee("002", "Jean"));
// For each employee, using departmentId as the key, construct
// a map containing lists of all employees that have that ID
Map<String, List<Employee>> empMap =
emps
.stream()
.collect(
Collectors.groupingBy(emp -> emp.departmentId)
);
for (Entry<?, ?> e : empMap.entrySet()) {
System.out.println(e.getKey() + "-->" + e.getValue());
}
class Employee {
public String departmentId;
public String name;
public Employee(String departmentId, String name) {
this.departmentId = departmentId;
this.name = name;
}
public String toString() {
return "(" + departmentId + " " + name + ")";
}
}
这会显示
001-->[(001 Jim), (001 June)]
002-->[(002 Bob), (002 Jean)]
另一个选项可以完成完全相同的操作,如下所示:
这会创建一个空 map 。然后它迭代员工列表并计算该键的值是否存在。如果是,则返回列表并将该条目添加到该列表中。如果没有,它会创建新的 ArrayList,然后为该列表添加员工,并将该列表存储在提供的键中。
Map<String, List<Employee>> emp2 = new HashMap<>();
for (Employee emp : emps) {
emp2.compute(emp.departmentId,
(ID, list) -> list == null ? new ArrayList<>()
: list).add(emp);
}
在这种情况下,我首选第一种方法。
关于java - 从 Java 8 中的列表创建多个 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58981801/