I am working on the Scala function below that explores the use of anonymous functions. Is there a way this could be recreated in Java? I have attached the Scala code as well as the Java code I have attempted.
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))
Above is in Scala. I have attempted to recreate this in Java but get an error
public static void filter(List<Integer> lst, Function <Integer,Boolean> func) {
List<Integer> res;
for (if (func.apply(lst)):
) {
}
}
Overall the code line I'm having difficulty recreating is this line: lst.foreach ((x:Int)=>if (fn(x)) res = x::res) from the scala code
Edit: I have attempted in Java again but I get an error Cannot invoke "java.util.List.stream()" because "res" is null
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, Function <Integer,Boolean> func) {
List<Integer> res = null;
res.stream().map(func).collect(Collectors.toList());
return 0;
}