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

Java是否支持类似Scala的匿名函数?如何复现对应列表过滤代码?

问题结论

Scala的该匿名函数过滤功能完全可以在Java 8及以上版本中复现。

你现有代码的错误原因

  • 返回值类型不匹配:filter方法需要返回过滤后的List<Integer>,你误写为int类型
  • 空指针问题:结果列表res被初始化为null,调用null对象的方法必然触发空指针异常
  • 逻辑错位:过滤操作应该遍历输入参数lst的元素,而非对空的res对象执行流操作
  • 遍历逻辑错误:首次编写的for循环语法不符合Java规范,没有定义遍历变量

实现方案1:完全对齐Scala原始逻辑

和你编写的Scala逻辑完全一致,遍历每个元素头插、最后反转顺序:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

public class FilterDemo {
    public static List<Integer> filter(List<Integer> lst, Function<Integer, Boolean> func) {
        List<Integer> res = new ArrayList<>();
        // 对应Scala的lst.foreach逻辑
        for (Integer x : lst) {
            if (func.apply(x)) {
                res.add(0, x); // 头插,和Scala的x::res效果一致
            }
        }
        Collections.reverse(res); // 对应Scala的res.reverse
        return res;
    }

    public static void main(String[] args) {
        Function<Integer, Boolean> fn = x -> x % 2 == 0;
        List<Integer> list = List.of(0,1,2,3,4,5,6,7,8,9); // 等价于Scala的List.range(0,10)
        System.out.println(filter(list, fn));
    }
}

实现方案2:Java Stream 简洁实现

Java标准库自带Predicate函数式接口,专门用于断言判断,配合Stream API可以直接完成过滤操作,无需手动遍历和反转,代码更简洁高效:

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

public class FilterDemo {
    public static List<Integer> filter(List<Integer> lst, Predicate<Integer> predicate) {
        return lst.stream()
                .filter(predicate) // 直接过滤满足条件的元素
                .collect(Collectors.toList());
    }

    public static void main(String[] args) {
        Predicate<Integer> fn = x -> x % 2 == 0;
        List<Integer> list = List.of(0,1,2,3,4,5,6,7,8,9);
        System.out.println(filter(list, fn));
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 01:06:03