总结一些java 8中常用的函数式接口
- 函数式接口: Predicate < T >
函数描述符: T ==> boolean
原始类型特化:IntPredicate, LongPredicate, DoublePredicate// 判断是否是正数 IntPredicate predicate = i -> (i > 0); // true predicate.test(5);
- 函数式接口: Consumer < T >
函数描述符: T ==> void
原始类型特化:IntConsumer,LongConsumer, DoubleConsumer// 输出数字到控制台 IntConsumer consumer = i -> System.out.println(i); //IntConsumer consumer = System.out::println; // 5 consumer.accept(5);
- 函数式接口: Function <T , R>
函数描述符: T ==> R
原始类型特化:
IntFunction < R >, IntToDoubleFunction, IntToLongFunction,
LongFunction < R >, LongToDoubleFunction, LongToIntFunction,
DoubleFunction < R >,
ToIntFunction < T >, ToDoubleFunction < T >, ToLongFunction < T >// 整型转字符串 IntFunction<String> int2StringFunc = i -> (i + ""); //"10" int2StringFunc.apply(10); // 字符串转整型 ToIntFunction<String> string2IntFunc = s -> Integer.parseInt(s); //ToIntFunction<String> string2IntFunc = Integer::parseInt; // 22 string2IntFunc.applyAsInt("22");
- 函数式接口: Supplier < T >
函数描述符: () ==> T
原始类型特化:BooleanSupplier,IntSupplier, LongSupplier, DoubleSupplier// 无中生有 Supplier<String> supplier = () -> "Welcome to my blog"; // "Welcome to my blog" supplier.get();
- 函数式接口: UnaryOperator < T >
函数描述符: T ==> T
原始类型特化:IntUnaryOperator, LongUnaryOperator, DoubleUnaryOperator// 平方 IntUnaryOperator operator = i -> i * i; // 25 operator.applyAsInt(5);
- 函数式接口: BinaryOperator< T >
函数描述符: (T, T) ==> T
原始类型特化:IntBinaryOperator, LongBinaryOperator, DoubleBinaryOperator// 两数之和 IntBinaryOperator sum = (i, j) -> i + j; // 11 sum.applyAsInt(5, 6);
- 函数式接口: BiPredicate < L, R >
函数描述符: (L, R) ==> boolean
原始类型特化:无// 判断数值是否相等 BiPredicate<Integer, String> biPredicate = (i, s) -> i == Integer.parseInt(s); // true biPredicate.test(5, "5"); // false biPredicate.test(5, "4");
- 函数式接口: BiConsumer < T, U >
函数描述符: (T, U) ==> void
原始类型特化:ObjIntConsumer < T >, ObjLongConsumer < T >, ObjDoubleConsumer < T >String format = "%s is %d years old"; BiConsumer<String, Integer> biConsumer = (s, i) -> { String result = String.format(format, s, i); System.out.println(result); }; // Tom is 15 years old biConsumer.accept("Tom", 15);
- 函数式接口: BiFunction < T, U, R >
函数描述符: (T, U) ==> R
原始类型特化:ToIntBiFunction < T, U >, ToDoubleBiFunction < T, U >, ToLongBiFunction < T, U >// 加入HashMap中 BiFunction<String, Integer, Map> biFunction = (s, i) -> { Map<String, Integer> map = new HashMap<>(); map.put(s, i); return map; }; // {"key" : 100} biFunction.apply("key", 100);