我有一个HashMap
,Integer
作为键,List<Employee>
作为值。我想从所有Values
HashMap
中获得所有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 感兴趣,因此请流式传输values
HashMap
,并且由于每个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 并收集为列表。
它不需要重新添加到列表中。