[英]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.