理解lamda表达式中的predicate 刚开始看,不是特别理解
假设如果有一个数组需要排序 需要封装一个函数
$arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
class A {
public function sout($arr, $fun) {
foreach ($arr as $item) {
$fun($item);
}
}
}
(new A())->sout($arr, $fun);
那传进去的参数就需要是一个匿名函数
$fun = function ($item) {
if($item % 2 == 1) {
echo $item . "\r\n";
}
};
类比到java
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
首先定义一个方法
private static void num(List<Integer> list, Test test) {
for (Integer num : list) {
test.test(num);
}
}
没有办法传入匿名的函数,就只能定义一个接口
interface Test {
public void test(Integer item);
}
Test test = (item) -> {
if (item %2 ==1) {
System.out.println(item);
}
};
num(list, test);
Predicate只是省略了自己定义接口
Predicate<Integer> predicate = (n) -> {
if (n % 2 ==1) {
return true;
}
return false;
};
private static void num(List<Integer> list, Predicate test) {
for (Integer num : list) {
if (test.test(num)) {
System.out.println(num);
}
}
}
num(list, predicate);