简体   繁体   中英

Convert Stream<Object[]> to List<Object> using java stream

I have a Stream<Student[]> object and I need to collect as List<Student>

If I use, obj.collect(Collectors.toList()) then I get List<Student[]>

Is there a better way to get this converted?

List<Object> flat = objArrs.stream()
                           .flatMap(Stream::of)
                           .collect(Collectors.toList());

or

List<Object[]> list = ...
List<Object> l = list.stream()
                     .flatMap(arr -> Stream.of(arr))
                     .collect(Collectors.toList());

How about this? you can using Stream#flatMap to merge all of Student[] in a List together.

stream.flatMap(students-> Stream.of(students)).collect(Collectors.toList());

The documentation says:

The flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the resulting elements into a new stream.

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