简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM