0

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;
}
2
  • 3
    Java has lambdas ... from Java 8 onwards. Commented Jun 24, 2021 at 10:50
  • Please do not vandalize your questions. Commented Jul 4, 2021 at 14:35

1 Answer 1

1

Yes, You can do like:

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
    }
}

Sign up to request clarification or add additional context in comments.

1 Comment

I think reversal is not needed. In scala x::res creates the resulting list in reverse order, so there an undoing reverse was needed. Also sorted then needed naturalOrder first. Not important, but Predicate<Integer>/``test` is a bit more concise as Function<Integer, Boolean>/apply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.