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

如何通过Java Stream从两个集合中筛选指定Customer记录?

问题:筛选不匹配城市列表的客户记录

类型与数据定义

class Customer{
    String custName;
    String custCity;
    // getter & setter
}

Set<Customer> custSet = new HashSet<>(); // 已填充若干记录

class City{
    Integer cityId;
    String cityName;
    // getter & setter
}
List<City> cityList = new ArrayList<>(); // 已填充若干记录

需求说明

需要从custSet中筛选出custCity与cityList中任意cityName都不匹配的记录。

示例数据

cityList [{cityId=1, cityName=NewYork},{cityId=2, cityName=Chicago}]
custSet [{custName=John, custCity=NewYork},{custName=Jill, custCity=Delhi}]

最终应选中{custName=Jill, custCity=Delhi}并存入新Set,因为Delhi不在cityList的城市名中。

尝试的错误代码

cityList.stream()
   .map(City::getCityName)
   .anyMatch(
     custSet.stream()
       .map(Customer::getCustCity)
       .collect(toSet())
       ::contains)

该代码无法得到移除匹配城市后的客户集合,寻求解决方案。


解决方案

核心思路

  1. 先将cityList中的所有城市名提取为一个Set,利用Set的O(1)查询效率提升性能;
  2. 遍历custSet,筛选出custCity不在上述城市名Set中的客户记录。

实现代码

import java.util.stream.Collectors;

// 1. 提取有效城市名集合
Set<String> validCityNames = cityList.stream()
    .map(City::getCityName)
    .collect(Collectors.toSet());

// 2. 筛选不匹配的客户
Set<Customer> unmatchedCustomers = custSet.stream()
    .filter(customer -> !validCityNames.contains(customer.getCustCity()))
    .collect(Collectors.toSet());

错误代码分析

你之前的代码逻辑方向完全错误:

  • 代码从cityList的流出发,用anyMatch判断客户城市集合中是否包含当前城市名,最终返回的是一个布尔值(仅表示是否存在重叠城市),而非筛选后的客户集合;
  • 完全没有对custSet进行筛选操作,自然无法得到目标结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:28:26