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

Java Streams:如何根据内部元素值过滤List<List<Health>>?

Java 过滤List<List>满足指定键值条件

核心实现思路

要筛选出同时满足bp值为notok且temp值为ok的子列表,可通过Java Stream API实现,核心逻辑是对外层列表的每个子列表做双条件校验。

基础实现代码

假设Health类提供getKey()和getValue()方法用于获取键值:

import java.util.List;
import java.util.stream.Collectors;

public class HealthDataFilter {
    public static void main(String[] args) {
        // 示例输入数据
        List<List<Health>> inputData = List.of(
                List.of(new Health("day", "mon"), new Health("bp", "ok"), new Health("temp", "ok")),
                List.of(new Health("day", "tues"), new Health("bp", "notok"), new Health("temp", "ok"))
        );

        // 过滤逻辑
        List<List<Health>> filteredResult = inputData.stream()
                .filter(subList -> {
                    // 校验子列表是否包含bp=notok
                    boolean bpCheck = subList.stream()
                            .anyMatch(h -> "bp".equals(h.getKey()) && "notok".equals(h.getValue()));
                    // 校验子列表是否包含temp=ok
                    boolean tempCheck = subList.stream()
                            .anyMatch(h -> "temp".equals(h.getKey()) && "ok".equals(h.getValue()));
                    // 两个条件同时满足才保留
                    return bpCheck && tempCheck;
                })
                .collect(Collectors.toList());

        // 输出结果
        filteredResult.forEach(System.out::println);
    }
}

// 定义Health类
class Health {
    private String key;
    private String value;

    public Health(String key, String value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return "Health{key='" + key + "', value='" + value + "'}";
    }
}

性能优化方案

如果子列表元素较多,可先将每个子列表转换为Map<String, String>,减少遍历次数,提升查找效率:

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class OptimizedHealthFilter {
    public static void main(String[] args) {
        List<List<Health>> inputData = // 你的输入数据

        List<List<Health>> filteredResult = inputData.stream()
                .filter(subList -> {
                    // 将子列表转为键值对Map
                    Map<String, String> healthMap = subList.stream()
                            .collect(Collectors.toMap(Health::getKey, Health::getValue));
                    // 直接通过key取值校验条件
                    return "notok".equals(healthMap.get("bp")) && "ok".equals(healthMap.get("temp"));
                })
                .collect(Collectors.toList());
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:55:31