微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Java 是否以与 Scala 类似的方式支持匿名函数?

如何解决Java 是否以与 Scala 类似的方式支持匿名函数?

我正在研究下面探索匿名函数使用的 Scala 函数。有没有办法在Java中重新创建它?我附上了 Scala 代码以及我尝试过的 Java 代码

def filter (lst:List[Int],fn:(Int)=>Boolean):List[Int] = 
{
var res:List[Int] = Nil
lst.foreach ((x:Int)=>if (fn(x)) res = x::res)
return res.reverse
}

val list = List.range(0,10)
println(filter(list,x => x % 2 == 0))

以上是在 Scala 中。 我试图用 Java 重新创建它,但出现错误

public static void filter(List<Integer> lst,Function <Integer,Boolean> func) {
    List<Integer> res;
    for (if (func.apply(lst)):
         ) {

    }

}

总的来说,我很难重新创建的代码行是这一行: lst.foreach ((x:Int)=>if (fn(x)) res = x::res) 来自Scala代码

编辑:我再次尝试使用 Java,但出现错误无法调用“java.util.List.stream()”,因为“res”为空

  Function <Integer,Boolean> fn =  x -> x % 2 == 0;
    List<Integer> list = Arrays.asList(1,2,3,5,6,7,8,9,10);
    
    System.out.println (filter(list,fn));

}
public static int filter(List<Integer> lst,Boolean> func) {
    List<Integer> res = null;
    res.stream().map(func).collect(Collectors.toList());


    return 0;
}

解决方法

是的,你可以这样做:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;


public class TestFun {
    public static void main(String[] args) {
        Function<Integer,Boolean> fn = x -> x % 2 == 0;

        List<Integer> res = filter(Arrays.asList(1,2,3,4),fn);
        System.out.println(res);
    }


    public static List<Integer> filter(List<Integer> list,Function<Integer,Boolean> func) {
        return list
                .stream() // convert into stream
                .filter(func::apply) // apply the filter
                .sorted(Collections.reverseOrder()) //reverse the order
                .collect(Collectors.toList()); // convert into List
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?