![](/img/trans.png)
[英]Is there any way to get list of values from HashMap contains of ArrayList of HashMaps?
[英]Best way to get list of id's from hashMap values
我有一个HashMap
,其中Integer
为键, List<Employee>
为值。 我想从HashMap
所有Values
中获取所有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());
由于您只对Ids感兴趣,因此流式传输HashMap
values
,并且因为每个都是List
,您将使用flatMap
,其余的可能很明显。 此外,因为这些是不同的,所以返回类型的Set
更有意义。
如果您仍然需要List
,请使用:
.... .map(Employee::getId)
.distinct()
.collect(Collectors.toList())
List<Long> ids = hm.values().stream().map(Employee::getId).collect(Collectors.toList());
在这里我们所做的是将值作为流和地图员工ID获取并收集为列表。
它不需要重新添加到列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.