Java 8 stream API, how to collect List to Object with several List fields

EraCat :

I want to get one Object with List<> fields from list of objects with no List<> fields.

This is my code:

public class ObjectDTO {
    private List<String> ids;
    private List<Date> times;
    private List<String> names;
    private List<String> details;

public class ObjectDTOHelper {
        private String id;
        private Date time;
        private String name;
        private String detail;
}

I supply List<ObjectDTOHelper> as input and want to get output just an object of ObjectDTO.

Which I can solve with multiple independent stream functions:

List<ObjectDTOHelper> helpers; //about 1000 elements

List<String> ids= helpers.stream().map(h -> h.id).collect(toList());
List<Date> times= helpers.stream().map(h -> h.time).collect(toList());
List<String> names= helpers.stream().map(h -> h.name).collect(toList());
List<String> details= helpers.stream().map(h -> h.detail).collect(toList());

new ObjectDTO(ids, times, name, detail)

Which I think is not the best solution, because I need do that more 100_000 times)

Can you help solve this more optimally?

Klitos Kyriacou :

One possible optimization to add to what you've done already is to preallocate the known exact amount of memory needed for all your lists:

List<ObjectDTOHelper> helpers = ...; //about 1000 elements
int size = helpers.size();

List<String> ids= helpers.stream().map(h -> h.id).collect(toCollection(()->new ArrayList<>(size)));
List<Date> times= helpers.stream().map(h -> h.time).collect(toCollection(()->new ArrayList<>(size)));
List<String> names= helpers.stream().map(h -> h.name).collect(toCollection(()->new ArrayList<>(size)));
List<String> details= helpers.stream().map(h -> h.detail).collect(toCollection(()->new ArrayList<>(size)));

new ObjectDTO(ids, times, name, detail)

If you have too many such fields, you can create your own Collector to pass to collect().

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145198&siteId=1