java streams - 如何使用键上的条件来平移集合映射中的所有值

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)

但它甚至没有编译

Era*_*ran 7

你有一些语法错误.

这应该产生你想要的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)