Introduction to the
Boolean valued function
Look at the source code
Elements of perceived
- The return value is
boolean
- There are abstract methods
test
- And not and not (
And, negate, or
) default method method,Implies that two Predicate objects can be used together - If you understand BiFunction, it’s easy to understand Predicate
test
public class PredicateTest {
public static void main(String[] args) {
PredicateTest test = new PredicateTest();
List<Integer> list = Arrays.asList(1.2.3.4.5.6.7.8.9.10);
test.printByCondition(list,l -> l%2= =0);/ / print even
System.out.println("\n"+"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
test.printByConditionNegate(list,l -> l%2= =0); / / print is not even
System.out.println("\n"+"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
test.printByConditionAnd(list,l -> l%2= =0,l -> l>4); //print even numbers greater than 4
System.out.println("\n"+"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
test.printByConditionOr(list,l -> l%2= =0,l -> l<4); Print even numbers or numbers less than 4
}
public void printByCondition(List<Integer> list, Predicate<Integer> predicate){
//l indicates an element in the list. // An element is output if it meets certain criteria
list.forEach( l -> { if (predicate.test(l)) System.out.print(l+""); });
}
public void printByConditionNegate(List<Integer> list, Predicate<Integer> predicate){
//l indicates an element in the list. // An element does not meet certain criteria
list.forEach( l -> { if (predicate.negate().test(l)) System.out.print(l+""); });
}
public void printByConditionAnd(List<Integer> list, Predicate<Integer> predicate1,Predicate<Integer> predicate2){
// An element satisfies both conditions
list.forEach( l -> { if (predicate1.and(predicate2).test(l)) System.out.print(l+""); });
}
public void printByConditionOr(List<Integer> list, Predicate<Integer> predicate1,Predicate<Integer> predicate2){
// An element satisfies a condition
list.forEach( l -> { if (predicate1.or(predicate2).test(l)) System.out.print(l+""); }); }}Copy the code
explain
- It is important to always keep in mind the meaning of a Lambda expression, that is, an abstract method in the implementation interface that will eventually be used
InterFaceClass.method
- Both arguments and return values are indispensable
summary
Function of Lambda expressions
- Transfer behavior, not just values
- Raising the level of abstraction
-
public void printByCondition(List<Integer> list, Predicate<Integer> predicate){ //l indicates an element in the list. // An element is output if it meets certain criteria list.forEach( l -> { if (predicate.test(l)) System.out.print(l+""); }); } Copy the code
- Look at this method alone, it only knows that if it satisfies some condition, but it doesn’t know exactly what condition, so it raises the level of abstraction. Right
-
- Apis are more reusable
- More flexible
- The same method can be replaced with lambda expressions at will, so it is more reusable and flexible