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

如何遍历JSON列表获取status为tagged的对象Id并终止循环

解决方案

问题分析

你现有代码的核心问题是用Collectors.groupingBy统计状态数量后,丢失了原始对象的Id信息,遍历统计结果只能判断状态是否存在,没法拿到对应对象的Id。另外要注意JSON里的状态是小写的"tagged",你代码里用了大写的"Tagged",这会导致匹配失败。

修正后的代码

直接遍历原始的List<StatusResponseSubCO>列表,找到第一个符合条件的对象后立即终止循环并获取Id:

HashMap<String, Object> json = parser.object();
if (json.containsKey("listOfId")) {
    ObjectMapper objectMapper = new ObjectMapper();
    StatusResponseCO mobileDcResponseDto = objectMapper.readValue(responseEntity, StatusResponseCO.class);
    List<StatusResponseSubCO> statusResponseCOS = mobileDcResponseDto.getListOfId();
    
    String targetId = null;
    for (StatusResponseSubCO item : statusResponseCOS) {
        // 严格匹配JSON中的小写状态值
        if ("tagged".equals(item.getStatus())) {
            targetId = item.getId();
            break; // 找到目标后立即终止循环
        }
    }
    
    if (targetId != null) {
        System.out.println("找到的tagged对象Id:" + targetId);
        // 此处可根据业务需求返回Id或执行其他逻辑
        return true;
    } else {
        // 未找到tagged状态的对象
        return false;
    }
}

优化方案(使用Stream API)

如果偏好Stream风格,可以用findFirst()实现短路查找,代码更简洁:

HashMap<String, Object> json = parser.object();
if (json.containsKey("listOfId")) {
    ObjectMapper objectMapper = new ObjectMapper();
    StatusResponseCO mobileDcResponseDto = objectMapper.readValue(responseEntity, StatusResponseCO.class);
    List<StatusResponseSubCO> statusResponseCOS = mobileDcResponseDto.getListOfId();
    
    Optional<String> targetIdOptional = statusResponseCOS.stream()
            .filter(item -> "tagged".equals(item.getStatus()))
            .map(StatusResponseSubCO::getId)
            .findFirst();
    
    if (targetIdOptional.isPresent()) {
        String targetId = targetIdOptional.get();
        System.out.println("找到的tagged对象Id:" + targetId);
        return true;
    } else {
        return false;
    }
}

关键注意事项

  • 实体类需补充getter方法:你的StatusResponseSubCO类要添加getId()和getStatus(),否则无法读取对象属性。
  • 大小写严格匹配:必须和JSON中的"tagged"小写保持一致,避免匹配失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 21:20:25