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

如何用Java 8 Streams检测整数列表中是否存在连续6个大于0的元素

Java判断整数列表是否存在连续6个大于0的元素

你之前写的y.stream().allMatch(num -> num > 0)逻辑完全不对——这个方法是检查整个列表所有元素都大于0,而你的需求是找「是否存在连续6个大于0的元素」,两者根本不是一回事。

下面给两种靠谱的实现方式:

方法一:普通循环(高效直观,优先推荐)

这种方法遍历列表时维护连续计数,一旦达到6就立刻返回结果,不用遍历完整个列表,性能最优。

import java.util.List;

public class WorkDayChecker {
    public static boolean hasConsecutiveSixWorkDays(List<Integer> dailyHours) {
        int consecutiveDays = 0;
        for (int hours : dailyHours) {
            if (hours > 0) {
                consecutiveDays++;
                // 连续工作天数达标,直接返回true
                if (consecutiveDays >= 6) {
                    return true;
                }
            } else {
                // 休息一天,重置连续计数
                consecutiveDays = 0;
            }
        }
        // 遍历完都没找到连续6天,返回false
        return false;
    }

    public static void main(String[] args) {
        List<Integer> x = List.of(0,0,0,6,0,7,9,0,0,8,9,0,1,0);
        System.out.println(hasConsecutiveSixWorkDays(x)); // 输出false

        List<Integer> y = List.of(0,0,4,7,8,0,9,1,5,7,8,6,4,7);
        System.out.println(hasConsecutiveSixWorkDays(y)); // 输出true
    }
}

方法二:Stream API实现(函数式风格)

如果偏好函数式编程,可以用anyMatch配合原子类维护连续计数,找到符合条件的情况就终止流:

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class WorkDayCheckerStream {
    public static boolean hasConsecutiveSixWorkDays(List<Integer> dailyHours) {
        AtomicInteger consecutiveDays = new AtomicInteger(0);
        return dailyHours.stream()
                .anyMatch(hours -> {
                    if (hours > 0) {
                        return consecutiveDays.incrementAndGet() >= 6;
                    } else {
                        consecutiveDays.set(0);
                        return false;
                    }
                });
    }

    public static void main(String[] args) {
        List<Integer> x = List.of(0,0,0,6,0,7,9,0,0,8,9,0,1,0);
        System.out.println(hasConsecutiveSixWorkDays(x)); // 输出false

        List<Integer> y = List.of(0,0,4,7,8,0,9,1,5,7,8,6,4,7);
        System.out.println(hasConsecutiveSixWorkDays(y)); // 输出true
    }
}

说明

  • 普通循环的写法更简洁,不需要额外依赖原子类,理解成本更低;
  • Stream的写法符合函数式编程习惯,但因为需要维护跨lambda的状态,所以用了AtomicInteger,性能和普通循环相差不大。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:12:32