描述:一元运算,接受一个T类型参数,输出一个与入参一模一样的值
源码:
package java.util.function; /** * Represents an operation on a single operand that produces a result of the * same type as its operand. This is a specialization of {@code Function} for * the case where the operand and result are of the same type. * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #apply(Object)}. * * @param <T> the type of the operand and result of the operator * * @see Function * @since 1.8 */ @FunctionalInterface public interface UnaryOperator<T> extends Function<T, T> { /** * Returns a unary operator that always returns its input argument. * * @param <T> the type of the input and output of the operator * @return a unary operator that always returns its input argument */ static <T> UnaryOperator<T> identity() { return t -> t; } }
测试代码:
System.out.println(UnaryOperator.identity().apply(10)); // 10 System.out.println(UnaryOperator.identity().apply(10.01)); // 10.01 System.out.println(UnaryOperator.identity().apply(false)); // false System.out.println(UnaryOperator.identity().apply("10")); // 10
也可以预先定义好T类型的参数,测试代码如下
UnaryOperator<Integer> b = x->x.intValue(); // lambda表达式,这样就只能输入Integer类型了 System.out.println(b.apply(10));