Sanjeev
Sanjeev

Reputation: 433

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?

Upvotes: 1

Views: 3123

Answers (2)

holi-java
holi-java

Reputation: 30686

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.

Upvotes: 2

Rahul Singh
Rahul Singh

Reputation: 19622

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());

Upvotes: 5

Related Questions