@FunctionalInterfacepublicinterfaceFunction<T,R> { /** * Applies this function to the given argument. * * @param t the function argument * @return the function result */Rapply(T t);
一般我们在对集合类进行处理的时候,会用到Function。
Map<String,Integer> nameMap =newHashMap<>();Integer value =nameMap.computeIfAbsent("name", s ->s.length());
@FunctionalInterfacepublicinterfaceIntFunction<R> { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result */Rapply(int value);}
@FunctionalInterfacepublicinterfaceToDoubleFunction<T> { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result */doubleapplyAsDouble(T value);}
@FunctionalInterfacepublicinterfaceLongToIntFunction { /** * Applies this function to the given argument. * * @param value the function argument * @return the function result */intapplyAsInt(long value);}
@FunctionalInterfacepublicinterfaceBiFunction<T,U,R> { /** * Applies this function to the given arguments. * * @param t the first function argument * @param u the second function argument * @return the function result */Rapply(T t,U u);
@FunctionalInterfacepublicinterfaceSupplier<T> { /** * Gets a result. * * @return a result */Tget();}
Consumer:接收一个参数,不返回值
Consumer接收一个参数,但是不返回任何值,我们看下Consumer的定义:
@FunctionalInterfacepublicinterfaceConsumer<T> { /** * Performs this operation on the given argument. * * @param t the input argument */voidaccept(T t);
看一个Consumer的具体应用:
//ConsumernameMap.forEach((name, age) ->System.out.println(name +" is "+ age +" years old"));
Predicate:接收一个参数,返回boolean
Predicate接收一个参数,返回boolean值:
@FunctionalInterfacepublicinterfacePredicate<T> { /** * Evaluates this predicate on the given argument. * * @param t the input argument * @return {@code true} if the input argument matches the predicate, * otherwise {@code false} */booleantest(T t);
@FunctionalInterfacepublicinterfaceIntUnaryOperator { /** * Applies this operator to the given operand. * * @param operand the operand * @return the operator result */intapplyAsInt(int operand);