使用Java流将两个大小相同(类型不同)的列表合并到域对象列表中 [英] Combine two lists of same size (and different type) into list of domain objects using java streams

查看:68
本文介绍了使用Java流将两个大小相同(类型不同)的列表合并到域对象列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个大小分别为idsresults的列表,我想用域对象创建新列表.

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

我使用的解决方案:

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?

推荐答案

我找到了一种使用番石榴zip运算符执行此操作的方法.

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

这篇关于使用Java流将两个大小相同(类型不同)的列表合并到域对象列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆