Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a List<Object[]> to Stream<Object>

I have a native query which returns a List<Object[]>. I want to convert this List to a Stream<Object>. These Objects are different columns from different tables of my database.

What is the best solution to do that?

Create a DTO and convert a List<DTO> to Stream<DTO>? How can I do that?

like image 795
Fizik26 Avatar asked Jan 23 '19 08:01

Fizik26


2 Answers

Assuming your DTO class has a proper constructor, you can write something like this:

List<Object[]> input = ...
Stream<DTO> dtos = input.stream().map(arr -> new DTO(arr[0], arr[1], ... , arr[n]);
like image 58
Eran Avatar answered Nov 13 '22 07:11

Eran


Use flatMap:

List<Object[]> objectsList = new ArrayList<>();
Stream<Object> objectStream = objectsList.stream()
        .flatMap(Arrays::stream);
like image 35
J-Alex Avatar answered Nov 13 '22 07:11

J-Alex