Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a method as a parameter in Java 8?

I don't understand how to use lambdas to pass a method as a parameter.

Considering the following (not compiling) code, how can I complete it to get it work ?

public class DumbTest {
    public class Stuff {
        public String getA() {
            return "a";
        }
        public String getB() {
            return "b";
        }
    }

    public String methodToPassA(Stuff stuff) {
        return stuff.getA();
    }

    public String methodToPassB(Stuff stuff) {
        return stuff.getB();
    }

    //MethodParameter is purely used to be comprehensive, nothing else...
    public void operateListWith(List<Stuff> listStuff, MethodParameter method) {
        for (Stuff stuff : listStuff) {
            System.out.println(method(stuff));
        }
    }

    public DumbTest() {
        List<Stuff> listStuff = new ArrayList<>();
        listStuff.add(new Stuff());
        listStuff.add(new Stuff());

        operateListWith(listStuff, methodToPassA);
        operateListWith(listStuff, methodToPassB);
    }

    public static void main(String[] args) {
        DumbTest l = new DumbTest();

    }
}
like image 265
Barium Scoorge Avatar asked Aug 27 '15 17:08

Barium Scoorge


2 Answers

Declare your method to accept a parameter of an existing functional interface type which matches your method signature:

public void operateListWith(List<Stuff> listStuff, Function<Stuff, String> method) {
    for (Stuff stuff : listStuff) {
        System.out.println(method.apply(stuff));
    }
}

and call it as such:

operateListWith(listStuff, this::methodToPassA);

As a further insight, you don't need the indirection of methodToPassA:

operateListWith(listStuff, Stuff::getA);
like image 127
Marko Topolnik Avatar answered Sep 23 '22 21:09

Marko Topolnik


Your MethodParameter should be some interface you define with a single method. This is referred to as a functional interface. You can then pass your methods in. A quick demonstration:

public interface Test{
    void methodToPass(string stuff);
}

[...]

public class DumbTest{
     //MethodParameter is purely used to be comprehensive, nothing else...
    public void operateListWith(List<Stuff> listStuff, Test method) {
        for (Stuff stuff : listStuff) {
            System.out.println(method(stuff));
        }
    }
    public DumbTest() {
        List<Stuff> listStuff = new ArrayList<>();
        //fill list
        operateListWith(listStuff, methodToPassA);
        operateListWith(listStuff, methodToPassB);
    }
}
like image 30
William Morrison Avatar answered Sep 22 '22 21:09

William Morrison