从哈希图值中获取 id 列表的最佳方法



我有一个HashMapInteger作为键,List<Employee>作为值。我想从所有ValuesHashMap中获得所有Ids

List<Long> ids = new ArrayList<>();
hm.forEach((key, value) -> {
List<Integer> c = value.stream()
.map(Employee::getId).collect(Collectors.toList());
ids.addAll(c);
}

这是我到目前为止尝试的方式。 有没有办法直接从HashMap的值流式传输并获取所有不同的值?

hm.values()
.stream()
.flatMap(List::stream)
.map(Employee::getId)
.collect(Collectors.toSet());

由于您只对 Id 感兴趣,因此请流式传输valuesHashMap,并且由于每个List(s(,您将使用flatMap,其余的可能很明显。此外,由于这些是不同的,正如您所说,返回类型的Set更有意义。

如果您仍然需要List只需使用:

.... .map(Employee::getId)
.distinct()
.collect(Collectors.toList())
List<Long> ids = hm.values().stream().map(Employee::getId).collect(Collectors.toList());

在这里,我们所做的是获取值作为流并映射员工 ID 并收集为列表。

它不需要重新添加到列表中。