我不明白如何使用lambdas将方法作为参数传递.
考虑以下(不编译)代码,如何完成它以使其工作?
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(); } }
解决方法
声明您的方法接受与您的方法签名匹配的现有功能接口类型的参数:
public void operateListWith(List<Stuff> listStuff,Function<Stuff,String> method) { for (Stuff stuff : listStuff) { System.out.println(method.apply(stuff)); } }
并称之为:
operateListWith(listStuff,this::methodToPassA);
作为进一步的见解,您不需要方法toTassA的间接:
operateListWith(listStuff,Stuff::getA);