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

如何在Java Stream中整合if逻辑,避免重复流处理

优化Stream重复处理的方案

你可以通过提取判断条件为Predicate的方式,把选择逻辑整合到Stream中,避免重复的流初始化和map操作:

System.out.println("Print the average of the negative numbers or the positive numbers? (n/p)");
String answer = scanner.nextLine();

// 根据输入选择对应的过滤条件
Predicate<Integer> filterCondition = answer.equals("n") 
    ? num -> num < 0 
    : num -> num > 0;

// 复用流处理流程,只替换filter条件
double average = inputs.stream()
        .mapToInt(Integer::valueOf) // 用方法引用简化写法
        .filter(filterCondition)
        .average()
        .getAsDouble();

优化点说明:

  • 把判断负数/正数的逻辑抽成Predicate<Integer>,根据用户输入动态选择,避免重复写两次几乎一样的流代码
  • 用Integer::valueOf方法引用替代lambda表达式,让代码更简洁
  • 整个流处理流程只执行一次,减少冗余

另外注意:如果输入的集合中没有符合条件的数(比如选了n但全是正数),getAsDouble()会抛出NoSuchElementException,原代码也存在这个问题,如果你想避免异常,可以用.orElse(0.0)或者.orElseThrow()自定义异常来处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 12:57:42