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

Java中随机IntStream过滤无结果问题排查

问题

我在水族箱模拟中用分钟代表年份,用Turtle记录类表示海龟(包含名称、孵化时间Instant、寿命Duration),定义MATURITY为4分钟,通过age()方法计算海龟年龄。我尝试用ThreadLocalRandom生成随机IntStream作为海龟List的索引,筛选年龄超过MATURITY的成熟海龟,返回Optional<Turtle>,但始终无结果,请问原因是什么?

相关代码

Turtle 记录类

record Turtle(
        String name ,
        Instant hatched ,
        Duration lifespan
)
{
    static final Duration MATURITY = Duration.ofMinutes ( 4 );

    Duration age ( ) { return Duration.between ( this.hatched , Instant.now ( ) ); }
}

Aquarium 主类

public class Aquarium
{
    public static void main ( String[] args )
    {
        System.out.println ( "INFO Demo start. " + Instant.now ( ) );

        // 测试数据
        List < Turtle > turtles =
                List.of (
                        new Turtle ( "Alice" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 3 ) ) , Duration.ofMinutes ( 17 ) ) ,
                        new Turtle ( "Bob" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 2 ) ) , Duration.ofMinutes ( 16 ) ) ,
                        new Turtle ( "Carol" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 1 ) ) , Duration.ofMinutes ( 18 ) ) ,
                        new Turtle ( "Davis" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 2 ) ) , Duration.ofMinutes ( 22 ) )
                );
        System.out.println ( "turtles = " + turtles );

        // 核心逻辑
        Optional < Turtle > anArbitraryMatureTurtle =
                ThreadLocalRandom
                        .current ( )
                        .ints ( 0 , turtles.size ( ) )
                        .filter (
                                ( int randomIndex ) -> turtles.get ( randomIndex ).age ( ).compareTo ( Turtle.MATURITY ) > 0
                        )
                        .mapToObj ( turtles :: get )
                        .findAny ( );
        System.out.println ( "anArbitraryMatureTurtle = " + anArbitraryMatureTurtle );

        // 模拟水族箱运行
        try { Thread.sleep ( Duration.ofMinutes ( 30 ) ); } catch ( InterruptedException e ) { throw new RuntimeException ( e ); }
        System.out.println ( "INFO Demo end. " + Instant.now ( ) );
    }
}
原因分析
  1. 初始测试数据无成熟个体:所有测试海龟的孵化时间都是当前时间减去1-3分钟,远小于MATURITY(4分钟)的要求。程序启动时执行筛选逻辑,此时没有海龟满足成熟条件,自然返回空Optional。
  2. 随机流的即时性限制:ThreadLocalRandom.ints()生成的流是即时处理的,仅在程序启动时执行一次筛选。后续即使海龟年龄增长到符合要求,这段筛选逻辑也不会重新触发。
解决方案

方案1:调整初始测试数据

直接创建孵化时间早于当前时间4分钟以上的海龟,让初始数据中就有成熟个体:

new Turtle ( "Eve" , Instant.now ( ).truncatedTo ( ChronoUnit.MINUTES ).minus ( Duration.ofMinutes ( 5 ) ) , Duration.ofMinutes ( 20 ) )

方案2:定时检测成熟海龟

使用定时任务周期性执行筛选逻辑,模拟水族箱运行过程中的动态检测:

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(() -> {
    Optional<Turtle> matureTurtle = turtles.stream()
            .filter(t -> t.age().compareTo(Turtle.MATURITY) > 0)
            .findAny();
    System.out.println("检测到成熟海龟:" + matureTurtle);
}, 0, 1, TimeUnit.MINUTES); // 每分钟执行一次检测

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 07:47:23