- 面向对象 (抽象数据,思考数据怎么做,编程时考虑数据怎么处理,比如打印一个什么数据)
- 函数式编程 (抽象行为,思考什么要做,考虑对这个数据做什么,比如对数据的操作就是打印)
java函数式编程接口很多,Consumer,Predicate,Function等等,都是被@FunctionalInterface注解的,可以lambda表达式传参数
name | type | description |
---|---|---|
Consumer | Consumer< T > | 接收T对象,不返回值 |
Predicate | Predicate< T > | 接收T对象并返回boolean |
Function | Function< T, R > | 接收T对象,返回R对象 |
Supplier | Supplier< T > | 提供T对象(例如工厂),不接收值 |
UnaryOperator | UnaryOperator< T > | 接收T对象,返回T对象 |
BiConsumer | BiConsumer<T, U> | 接收T对象和U对象,不返回值 |
BiPredicate | BiPredicate<T, U> | 接收T对象和U对象,返回boolean |
BiFunction | BiFunction<T, U, R> | 接收T对象和U对象,返回R对象 |
BinaryOperator | BinaryOperator< T > | 接收两个T对象,返回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();
}
}