简体   繁体   English

Java 流:收集流<int[]>列出<int[]>

[英]Java stream: Collect Stream<int[]> to List<int[]>

I try to get my head around java streams.我试图让我的头脑围绕 Java 流。

Atm I have this construct which does not work: 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()));
}

The hierarchy is:层次结构是:

  • Process过程
    • Event事件
      • Property财产

Process::getEventList returns a list of Event objects Process::getEventList 返回一个Event对象列表

event.getPropertie("whitelist") returns a Property objects which hast the method getIntArray() event.getPropertie("whitelist")返回一个具有getIntArray()方法的Property对象

event.getPropertie() gives me an int-array. event.getPropertie()给了我一个整数数组。


How do I collect these array into a List of arrays?如何将这些数组收集到数组列表中?

Thanks!谢谢!


You can't use forEach() as it takes a Consumer , meaning it will consume the stream, but can't return anything (so nothing to collect).您不能使用forEach()因为它需要一个Consumer ,这意味着它会消耗流,但不能返回任何东西(所以没有什么可收集的)。

You need flatMap to stream the internal eventList as follows您需要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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM