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

如何使用Java8 Stream从两个不等长List生成pid对应location的Map

实现方案

建议先将addressList转换为pid对应location的预查询Map,再关联personList生成最终结果,避免双重循环带来的O(n*m)时间复杂度,天然适配两个列表长度不等的场景。

步骤1:预构建地址pid到location的映射

先把地址列表转成可快速查询的pid-location映射,同时处理可能的重复pid问题:

import java.util.stream.Collectors;

// 重复pid时默认取新值覆盖旧值,可根据业务需求调整合并规则
Map<String, String> addrPidToLocMap = addressList.stream()
       .collect(Collectors.toMap(
            Address::getPid,
            Address::getLocation,
            (oldLoc, newLoc) -> newLoc
        ));

步骤2:关联personList生成最终Map

场景1:保留所有person的pid,无对应地址时值为null

Map<String, String> resultMap = personList.stream()
       .collect(Collectors.toMap(
            Person::getPid,
            person -> addrPidToLocMap.get(person.getPid()),
            (oldVal, newVal) -> newVal // person存在重复pid时的合并规则,无重复可删除
        ));

场景2:仅保留两个列表共有的pid,过滤无对应地址的person

Map<String, String> resultMap = personList.stream()
       .filter(person -> addrPidToLocMap.containsKey(person.getPid()))
       .collect(Collectors.toMap(
            Person::getPid,
            person -> addrPidToLocMap.get(person.getPid()),
            (oldVal, newVal) -> newVal
        ));

如果你需要返回指定的HashMap实现,可使用四参数版的toMap方法指定容器类型:

HashMap<String, String> resultMap = personList.stream()
   .filter(person -> addrPidToLocMap.containsKey(person.getPid()))
   .collect(Collectors.toMap(
        Person::getPid,
        person -> addrPidToLocMap.get(person.getPid()),
        (oldVal, newVal) -> newVal,
        HashMap::new
    ));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:06:05