Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two lists of same size (and different type) into list of domain objects using java streams

I'm having two lists of same size ids and results and I want to create new list with domain objects.

List<Id> ids = ...

List<Result> results = redisTemplate.opsForValue().multiGet.get(ids);

List<DomainObject> list = // list of domain objects new DomainObject(id, result);

Solution that I've used:

List<DomainObject> list = new ArrayList<>(ids.size());
for (int i = 0; i < ids.size(); i++) {
    list.add(new DomainObject(ids.get(i), results.get(i)));
}

Is there any more elegant way to do it eg. using streams?

like image 347
pixel Avatar asked Mar 02 '18 15:03

pixel


2 Answers

The equivalent of this way with Streams would be :

List<DomainObject> list = IntStream.range(0, ids.size())
                            .mapToObj(i -> new DomainObject(ids.get(i), results.get(i))) 
                            .collect(Collectors.toList());

Or take a look at Iterate two Java-8-Streams

like image 163
azro Avatar answered Oct 20 '22 22:10

azro


I've found a way to do it using guava zip operator.

List<DomainObject> list = Streams.zip(ids.stream(), results.stream(), DomainObject::new)
                            .collect(Collectors.toList());
like image 23
pixel Avatar answered Oct 20 '22 22:10

pixel