如何将List<Phone>与List<PhoneTwo>两个列表合并为包含phone字段的Combined对象列表?
解决Java Stream合并两个列表为Combined对象列表的问题
嘿,我来帮你搞定这个Stream合并的问题!你之前用flatMap的思路有点走偏了——flatMap是用来把每个元素拆解成子流再扁平化的,而你现在需要的是合并两个独立的流,然后把每个元素转成Combined对象。
正确的实现思路
其实很简单,我们可以用Stream.concat()把两个列表的流合并,再分别把Phone和PhoneTwo映射成Combined实例,最后收集成列表即可。
完整代码示例
首先假设你的Combined类是这样的(如果还没定义,需要先补上):
class Combined { private String phone; // 带参构造器,方便直接初始化 public Combined(String phone) { this.phone = phone; } // 或者无参构造+setter,根据你的需求选择 public Combined() {} public void setPhone(String phone) { this.phone = phone; } // getter方法 public String getPhone() { return phone; } }
然后合并列表的核心代码如下:
// 合并两个列表为Combined列表 List<Combined> combinedList = Stream.concat( // 把List<Phone>转成Stream<Combined> employee.getPhones().stream() .map(phone -> new Combined(phone.getPhone())), // 把List<PhoneTwo>转成Stream<Combined> employee.getPhonesTwo().stream() .map(phoneTwo -> new Combined(phoneTwo.getPhone())) ) .collect(Collectors.toList()); // 最后把合并后的列表设置到employee的combined字段 employee.setCombined(combinedList);
为什么你之前的flatMap用法不对
你之前尝试在flatMap里嵌套另一个流,这不是flatMap的正确使用场景。flatMap的作用是对原流中的每个元素,生成一个新的子流,然后把所有子流合并成一个大流——比如把一个列表的列表拆成单个元素的流。而你现在是要合并两个完全独立的流,用Stream.concat()才是最直接、可读性最高的选择。
(可选)如果一定要用flatMap的写法
虽然不推荐(因为需要类型判断,可读性差),但如果想尝试用flatMap实现,可以把两个列表放到一个集合里,再扁平化处理:
List<Combined> combinedList = Stream.of(employee.getPhones(), employee.getPhonesTwo()) .flatMap(Collection::stream) .map(item -> { Combined combined = new Combined(); if (item instanceof Phone) { combined.setPhone(((Phone) item).getPhone()); } else if (item instanceof PhoneTwo) { combined.setPhone(((PhoneTwo) item).getPhone()); } return combined; }) .collect(Collectors.toList());
这种写法不如concat清晰,因为需要额外的类型判断,所以更推荐第一种方案。
内容的提问来源于stack exchange,提问作者hades
相关产品推荐
相关产品推荐

