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

如何从响应的对象列表及嵌套对象中动态筛选指定数据

问题解决:动态筛选嵌套对象中指定类型的金额值

需求说明

需要从嵌套结构的响应数据中,动态筛选出所有functionType为LIMIT的functionAmount值,替代原有的硬编码逻辑,同时修复原代码中的Stream语法错误和异常风险。

修复后的完整代码

// 优化后的代码,处理嵌套空值并实现动态筛选
Optional<String> limitAmount = Optional.ofNullable(response)
        .map(Response::getUsers)
        .stream()
        .flatMap(List::stream)
        .map(UserOutput::getFunctions)
        .flatMap(List::stream)
        .map(FunctionAuthorityInfo::getFunctionAuthorities)
        .flatMap(List::stream)
        .filter(authority -> "LIMIT".equals(authority.getFunctionType()))
        .map(FunctionAuthority::getFunctionAmount) // 修复方法引用,去掉多余括号
        .findFirst();

// 安全获取结果,可设置默认值
String resultAmount = limitAmount.orElse("0");

关键优化点

  • 消除硬编码:通过flatMap逐层展开嵌套的集合(users → functions → functionAuthorities),不再固定取第一个元素,遍历所有可能的匹配项
  • 修复方法引用错误:原代码中FunctionAuthority::getFunctionAuthorityAmount()的写法错误,方法引用不能加括号,且需与实体类的getter方法名对应(原数据字段为functionAmount,对应getter应为getFunctionAmount)
  • 避免异常与空指针:用Optional包裹响应对象,结合map/flatMap自动跳过空集合;用findFirst()返回Optional<String>替代get(),彻底避免无匹配项时抛出NoSuchElementException
  • 简化冗余判断:去掉原代码中多层if(集合.size()>0)的冗余判断,Stream会自动忽略空集合,代码更简洁

原数据结构参考

{
    "users": [
        {
            "userId": "78888",
            "functions": [
                {
                    "functionCriteria": {
                        "functionParameter1": "GLOBAL",
                        "functionId": "77888"
                    },
                    "functionAuthorities": [
                        {
                            "functionType": "INITIALIZE",
                            "functionAmount": "250"
                        },
                        {
                            "functionType": "LIMIT",
                            "functionAmount": "2500"
                        }
                    ]
                }
            ]
        }
    ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 02:47:12