[英]Java stream: Collect Stream<int[]> to List<int[]>
我試圖讓我的頭腦圍繞 Java 流。
Atm 我有這個不起作用的構造:
List<int[]> whiteLists = processes.stream()
.map(Process::getEventList)
.forEach(eventList -> eventList.stream()
.map(event -> event.getPropertie("whitelist"))
.map(propertie -> propertie.getIntArray())
.collect(Collectors.toList()));
}
層次結構是:
Process::getEventList 返回一個Event
對象列表
event.getPropertie("whitelist")
返回一個具有getIntArray()
方法的Property
對象
event.getPropertie()
給了我一個整數數組。
如何將這些數組收集到數組列表中?
謝謝!
您不能使用forEach()
因為它需要一個Consumer
,這意味着它會消耗流,但不能返回任何東西(所以沒有什么可收集的)。
您需要flatMap來流式傳輸內部eventList
,如下所示
List<int[]> whiteLists = processes.stream()
.flatMap(p -> p.getEventList().stream())
.map(event -> event.getPropertie("whitelist"))
.map(propertie -> propertie.getIntArray())
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.