简体   繁体   中英

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

I try to get my head around java streams.

Atm I have this construct which does not work:

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

event.getPropertie("whitelist") returns a Property objects which hast the method getIntArray()

event.getPropertie() gives me an int-array.


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).

You need flatMap to stream the internal eventList as follows

List<int[]> whiteLists = processes.stream()
                                  .flatMap(p -> p.getEventList().stream())
                                  .map(event -> event.getPropertie("whitelist"))
                                  .map(propertie -> propertie.getIntArray())
                                  .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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