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

如何用Java 8 Stream改写按userId不区分大小写筛选Map值的方法?

问题描述

我有一个包含userId属性的UserCourseEntity类,代码如下:

@AllArgsConstructor
@Getter
@ToString
public static class UserCourseEntity {
    private String userId;
}

同时我还有一个以UserCourseEntity对象为值的Map:

public final Map<String, UserCourseEntity> userCourses;

方法getUserCoursesByUserID接收UserCourseEntity的userId属性作为参数,需要检查userCourses中是否存在userId与传入id不区分大小写匹配的元素(使用equalsIgnoreCase())。若存在则存入列表返回,否则抛出异常。现有实现代码如下,请问能否用Java 8 Stream重新实现该方法?

现有实现代码:

public List<UserCourseEntity> getUserCoursesByUserID(String userId) {
    List<UserCourseEntity> list = new ArrayList<>();
    for (Map.Entry<String, UserCourseEntity> entry : userCourses.entrySet()) {
        UserCourseEntity userCourseEntityValue = entry.getValue();
        String key = entry.getKey();
        boolean isExist = userCourseEntityValue.getUserId().equalsIgnoreCase(userId);
        
        if (!isExist) {
            continue;
        } else {
            if (userCourseEntityValue.getUserId().equalsIgnoreCase(userId)) {
                list.add(userCourses.get(key));
            }
        }
    }
    if (list.isEmpty()) {
        logger.error("No data found");
        throw new SpecificException("No data found with the given details");
    }
    return list;
}
优化实现(Java 8 Stream版本)

当然可以,用Stream重写后逻辑更简洁高效,代码如下:

public List<UserCourseEntity> getUserCoursesByUserID(String userId) {
    List<UserCourseEntity> result = userCourses.values()
            .stream()
            .filter(entity -> entity.getUserId().equalsIgnoreCase(userId))
            .collect(Collectors.toList());

    if (result.isEmpty()) {
        logger.error("No data found");
        throw new SpecificException("No data found with the given details");
    }
    return result;
}

关键优化点:

  • 直接遍历Map的values()集合,无需处理Entry的key,因为我们只需要值对象的userId属性做匹配
  • 用filter()方法一次性完成筛选逻辑,移除了原代码中重复的equalsIgnoreCase()判断
  • 借助collect(Collectors.toList())直接将流转换为目标列表,省去手动初始化列表并添加元素的步骤

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 16:03:37