You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java 8 Stream API将两个不同对象列表合并为单对象列表

Java 8 Stream 实现两个列表按位置映射组装对象

实现思路

Java 8 原生 Stream 没有提供双流按位合并的 zip 操作,要实现两个等长列表对应位置值的映射,最直接的方式是遍历合法索引范围,通过索引分别从两个列表取出对应位置的元素,再构造目标对象。

完整实现代码

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Prediction {
    int id;
    String rep;

    // 需提供对应参数的构造方法,支持直接传入id和rep初始化
    public Prediction(int id, String rep) {
        this.id = id;
        this.rep = rep;
    }
}

public class ListMappingDemo {
    public static void main(String[] args) {
        List<Integer> ids = Arrays.asList(1, 2, 3);
        List<String> reps = Arrays.asList("abc", "pqr", "xyz");

        List<Prediction> results = IntStream.range(0, ids.size())
                .mapToObj(index -> new Prediction(ids.get(index), reps.get(index)))
                .collect(Collectors.toList());
    }
}

场景适配说明

  • 如果Prediction类没有提供全参构造方法,可以在流的map阶段手动创建对象后赋值属性:
List<Prediction> results = IntStream.range(0, ids.size())
        .mapToObj(index -> {
            Prediction prediction = new Prediction();
            prediction.id = ids.get(index);
            prediction.rep = reps.get(index);
            return prediction;
        })
        .collect(Collectors.toList());
  • 如果两个列表长度可能不一致,建议提前取两个列表长度的最小值作为遍历上界,避免抛出索引越界异常:
int minSize = Math.min(ids.size(), reps.size());
List<Prediction> results = IntStream.range(0, minSize)
        .mapToObj(index -> new Prediction(ids.get(index), reps.get(index)))
        .collect(Collectors.toList());
  • 该实现是Java 8原生API下性能最优、可读性最高的方案,无需引入任何第三方依赖。

内容的提问来源于stack exchange,提问作者user3812288

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 05:09:18