1

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?

4
  • The better way is: create stream of Student (e.g. from List<Student>), then you won't have these problems. Commented Jun 1, 2017 at 16:20
  • I have a mapping function which returns Stream<Student[]> so I could not build Stream<Student> Commented Jun 1, 2017 at 16:21
  • Change the design then. Commented Jun 1, 2017 at 16:22
  • 1
    Really, having a Stream<Student[]> shows a flaw in the design. If you have the chance, you should try to fix the design instead of trying to find a workaround that would make the badly designed solution work anyways. Commented Jun 1, 2017 at 17:23

2 Answers 2

5
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());
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.