Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/c5113620/article/details/89208993
- Object (abstract data, how do think the data, consider how the data processing program, such as a print what data) for
- Functional Programming (abstract behavior, thinking what to do, think about what to do on this data, such as operations on the data that is printed)
java functional programming interfaces lot, Consumer, Predicate, Function, etc., are being @FunctionalInterface annotated, you can pass parameters lambda expression
name | type | description |
---|---|---|
Consumer | Consumer< T > | Receiving the object T, does not return value |
Predicate | Predicate< T > | Receiving the object and returns a boolean T |
Function | Function< T, R > | T receiving object, and returns the object R |
Supplier | Supplier< T > | Providing an object T (e.g. plant) does not receive a value |
UnaryOperator | UnaryOperator< T > | T receiving object, and returns the object T |
BiConsumer | BiConsumer<T, U> | T and U receiving objects objects, does not return value |
BiPredicate | BiPredicate<T, U> | T and U receiving objects objects, returns a boolean |
BiFunction | BiFunction<T, U, R> | T and U objects receiving object, and returns the object R |
BinaryOperator | BinaryOperator< T > | T receives two objects, the object returns T |
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
public class Test {
public static void main(String[] args) {
//Consumer< T >, take T no return
Test.cons("abc",new MyCons());
//lambda for Consumer< T >, str is T
Test.cons("abc",str->{if("abc".equals(str)) System.out.println(str);});
//Predicate< T >, take T return boolean
System.out.println(Test.pred("abc",new MyPred()));
//lambda for Predicate< T >, str is T
System.out.println(Test.pred("abc",str->{if("abc".equals(str)) return true;return false;}));
//Function< T, R >, take T return R
System.out.println(Test.func("abc",new MyFunc()));
//lambda for Function< T, R >, str is T
System.out.println(Test.func("abc",str->new StringBuilder(str).reverse().toString()));
}
public static void cons(String str, Consumer<String> consumer){
consumer.accept(str);
}
public static boolean pred(String str, Predicate<String> predicate){
return predicate.test(str);
}
public static String func(String str, Function<String,String> function){
return function.apply(str);
}
}
class MyCons implements Consumer<String>{
@Override
public void accept(String s) {
if("abc".equals(s)) System.out.println(s);
}
}
class MyPred implements Predicate<String>{
@Override
public boolean test(String s) {
if("abc".equals(s)) return true;
return false;
}
}
class MyFunc implements Function<String,String>{
@Override
public String apply(String s) {
return new StringBuilder(s).reverse().toString();
}
}