Bic*_*ick 3 java java-8 java-stream
我有一张地图.让我们说吧
Map<Long, List<MyObj>>
Run Code Online (Sandbox Code Playgroud)
我想在所有MyObj中创建一个长数组,其中键(long)在另一个set()中找到
anotherSet.contains(long)
Run Code Online (Sandbox Code Playgroud)
使用java流.
我试过了
map.entrySet()
.stream()
.filter(e->anotherSet(e.getKey()))
.flatMap(e.getValue)
.collect(Collectors.toList);
Run Code Online (Sandbox Code Playgroud)
但它甚至没有编译
你有一些语法错误.
这应该产生你想要的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 ()
Run Code Online (Sandbox Code Playgroud)
如果要生成数组而不是a List,请使用:
MyObj[] filteredArray =
map.entrySet()
.stream()
.filter(e->anotherSet.contains(e.getKey()))
.flatMap(e-> e.getValue().stream())
.toArray(MyObj[]::new);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
499 次 |
| 最近记录: |