Java8 - UnaryOperator接口示例|功能接口教程

274 阅读2分钟

java.util.function.UnaryOperator

UnaryOperator是java.util.function包中的一个功能接口,它对一个操作数进行操作并返回相同操作数类型的结果。这是用lambdaexpressions/metod/constructor引用指定的。

UnaryOperator的代码签名

@FunctionalInterface  
public interface UnaryOperator extends Function {    
    static  UnaryOperator identity() {  
        return t -> t;  
    }  
}  

UnaryOperator扩展了Function接口,它从函数接口扩展了抽象的应用。函数接口有默认的andThen()和compose方法

Lamda UnaryOperator方法示例

这是一个使用UnaryOperator与lambda表达式用法的例子

UnaryOperator unaryOperator = value -> value* value;  
System.out.println(unaryOperator.apply(6));  
System.out.println(unaryOperator.apply(6));  

静态身份方法示例

它有一个唯一的静态方法,用来返回输入值。下面是这个方法的一个使用例子

UnaryOperator IdentityUnaryOperator = UnaryOperator.identity();  
System.out.println(IdentityUnaryOperator.apply(25));  

默认方法和组合示例

该方法从Function接口扩展而来。andThen和compose的区别在于参数执行的顺序 andThen - 先运行被调用的函数,最后运行参数 compose - 先运行参数,最后调用函数

UnaryOperator UnaryOperator1 = value -> value * value;  
UnaryOperator UnaryOperator2 = value -> value * 10;  
System.out.println(UnaryOperator1.andThen(UnaryOperator2).apply(3));  
System.out.println(UnaryOperator1.compose(UnaryOperator2).apply(3));  

方法参考示例

这是一个使用方法引用的功能接口的例子。

UnaryOperator methodRef = String::toLowerCase;  
System.out.println(methodRef.apply("CLOUDHADOOP"));  

原始单项运算符

有三个原始单项运算符,分别是Integer、Long和Double。所有这些都只包含一个抽象的方法。所有这些操作符都接受相应的值类型并输出相同的输出类型的值。所有这些都可以用lambda表达式、传递参数、方法引用来分配,所有这些都定义在java.util.function包中。所有这些都将作为一个单独的参数来使用。

IntUnaryOperator使用实例

它有一个唯一的抽象方法 - applyAsInt 它是一个功能接口,接收一个整数值,只产生整数。

IntUnaryOperator IncrementInteger = (value) -> value +1;  
System.out.println(IncrementInteger.applyAsInt(9));  

LongUnaryOperator接口用法

这是一个功能接口,接受长的输入,只输出长的值,唯一的抽象方法是 applyAsLong

LongUnaryOperator decrementLong = (value) -> value + 1;  
System.out.println(decrementLong.applyAsLong(998756));  

DoubleUnaryOperator使用实例

DoubleUnaryOperator接收双倍值并只输出双倍值。它只有一个抽象方法 - double applyAsDouble(double operand); 默认方法 - andThen, compose方法

DoubleUnaryOperator doubleUnaryOperatorExample = (value) -> value+value;  
System.out.println(doubleUnaryOperatorExample.applyAsDouble(5));  
System.out.println(doubleUnaryOperatorExample.applyAsDouble(25.2));