1,定义函数式接口
package com.xingyuezhiyun.practice.lambada;
@FunctionalInterface
public interface PickerSelector<T extends Fruit> {
boolean pick(T fruit);
}
2,提供处理函数并调用
package com.xingyuezhiyun.practice.lambada;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String [] args) {
List<Fruit> fruitList = Arrays.asList(new Fruit("aaa", "red"){}, new Fruit("bbb", "blue"){});
System.out.println(pickFruit(fruitList, new RedInstance()));
System.out.println(pickFruit(fruitList, new BlueInstance()));
System.out.println(pickFruit(fruitList, fruit -> fruit.getColor().equals("red")));
}
public static List<Fruit> pickFruit(List<Fruit> fruitList, PickerSelector<Fruit> pickerSelector){
List<Fruit> result = new ArrayList<>();
fruitList.forEach(fruit -> {
if (pickerSelector.pick(fruit)){
result.add(fruit);
}
});
return result;
}
}
函数式接口 函数描述符
Predicate<T> (T) -> boolean
Consumer<T> (T) -> void
Function< T, R > (T) -> R
Supplier<T> ( ) -> T
UnaryOperator<T> (T) -> T
BinaryOperator<T> (T, T) -> T
BiPredicate<L, R> (L, R) -> boolean
BiConsumer<T, U> (T, U) -> void
BiFunction<T, U, R> (T, U) -> R