[英]java streams - how to flat all values from map of collections using condition on the key
I have a Map. 我有一张地图。 Let's say
让我们说吧
Map<Long, List<MyObj>>
I want to create a long array where of all MyObj where the key (long) is found in another set() 我想在所有MyObj中创建一个长数组,其中键(long)在另一个set()中找到
anotherSet.contains(long)
using java stream. 使用java流。
I tried 我试过了
map.entrySet()
.stream()
.filter(e->anotherSet(e.getKey()))
.flatMap(e.getValue)
.collect(Collectors.toList);
But it doesnt even compile 但它甚至没有编译
You had a few syntax errors. 你有一些语法错误。
This should produce your desired List
: 这应该产生你想要的
List
:
List<MyObj> filteredList =
map.entrySet()
.stream()
.filter(e->anotherSet.contains(e.getKey())) // you forgot contains
.flatMap(e-> e.getValue().stream()) // flatMap requires a Function that
// produces a Stream
.collect(Collectors.toList()); // you forgot ()
If you want to produce an array instead of a List
, use : 如果要生成数组而不是
List
,请使用:
MyObj[] filteredArray =
map.entrySet()
.stream()
.filter(e->anotherSet.contains(e.getKey()))
.flatMap(e-> e.getValue().stream())
.toArray(MyObj[]::new);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.