java.util.function.UnaryOperator
是一个功能接口,它扩展了java.util.function.Function
接口。 UnaryOperator
接口表示一个操作,它接受一个参数并返回与其输入参数相同类型的结果。
注 - 函数方法
apply()
和默认方法(andThen()
和compose()
)从Function
接口继承到UnaryOperator
。
示例#1
以下示例显示如何使用带有lambda表达式的UnaryOperator的apply()
方法。
文件:UnaryOperatorExample1.java -
package com.jb51.cc.tutorial.lambda;
import java.util.function.UnaryOperator;
/**
* @author jb51.cc
*/
public class UnaryOperatorExample1 {
public static void main(String[] args) {
UnaryOperator<Integer> operator = t -> t * 2;
System.out.println(operator.apply(5));
System.out.println(operator.apply(10));
System.out.println(operator.apply(15));
}
}
执行上面代码,得到以下结果:
10
20
30
示例#2
以下示例显示如何使用具有lambda表达式的UnaryOperator
的默认方法(andThen()
和compose()
)。
package com.jb51.cc.tutorial.lambda;
import java.util.function.UnaryOperator;
/**
* @author jb51.cc
*/
public class UnaryOperatorExample2 {
public static void main(String[] args) {
UnaryOperator<Integer> operator1 = t -> t + 10;
UnaryOperator<Integer> operator2 = t -> t * 10;
// Using andThen()
int a = operator1.andThen(operator2).apply(5);
System.out.println(a);
// Using compose()
int b = operator1.compose(operator2).apply(5);
System.out.println(b);
}
}
执行上面代码,得到以下结果:
150
60