四种函数型接口实现代码:
Consumer:
public class TestConsumer {
public static void main(String[] args) {
Consumer<String> c = (e)->System.out.println("今天天气:" + e);
c.accept("多云");
m("晴天", e-> System.out.println("今天天气:" + e));
}
public static void m(String s , Consumer<String> cs){
cs.accept(s);
}
}
运行结果:
今天天气:多云
今天天气:晴天
Supplier:
public class TestSupplier {
public static void main(String[] args) {
Supplier<Integer> sp = () -> {
int nums = 0;
for (int i = 0; i < 50; i++) {
nums += i;
}
return nums;
};
int sum = sp.get();
System.out.println(sum);
int n = m(50, () -> new Random().nextInt(500));
System.out.println(n);
}
public static int m(Integer i, Supplier<Integer> sp) {
int nums = 0;
for (int j = 1; j <= i; j++) {
nums += sp.get();
}
return nums;
}
}
运行结果:
1225
12110
随机
Function:
public class TestFunction {
public static void main(String[] args) {
List<String> li = new ArrayList<String>();
li.add("阿杰");
li.add("光芒");
li.add("公民");
li.add("阿辉");
int nums = m(li, (e)-> {if(e.startsWith("阿")){return 1;}
else{return 0;}
} );
System.out.println(nums);
}
public static int m(List<String> li, Function<String,Integer> ft){
int nums = 0;
for (String string : li) {
nums += ft.apply(string);
}
return nums;
}
}
运行结果:
2
Predicate:
public class TestEmployee {
public static void main(String[] args) {
Employee emp = new Employee("阿杰", 21,"男");
Employee emp1 = new Employee("公民", 23,"男");
Employee emp2 = new Employee("光芒", 22,"男");
List<Employee> li = new ArrayList<Employee>();
li.add(emp);
li.add(emp1);
li.add(emp2);
List<Employee> newLi = m(li, (e)->e.getName().startsWith("阿"));
for (Employee emps : newLi) {
System.out.println(emps);
}
}
public static List<Employee> m(List<Employee> li ,Predicate<Employee> pd){
List<Employee> newli = new ArrayList<Employee>();
for (Employee emp : li) {
if(pd.test(emp)){
newli.add(emp);
}
}
return newli;
}
}
运行结果:
Employee [name=阿杰, age=21, sex=男]