如何在Java的Lambda表达式中使用UnaryOperator 接口?
UnaryOperator<T>是一个功能,它扩展了接口功能的接口。它表示一个接受参数并返回与其输入参数相同类型的结果的操作。Function接口中的apply()方法和默认方法:andThen()和compose()是从UnaryOperator接口继承的。甲拉姆达表达和方法参考可以使用UnaryOperator对象作为其目标。
语法
@FunctionalInterface public interface UnaryOperator<T> extends Function<T, T>
示例1
import java.util.function.UnaryOperator;
public class UnaryOperatorTest1 {
public static void main(String[] args) {
UnaryOperator<Integer> operator = t -> t * 2; // lambda expression System.out.println(operator.apply(5));
System.out.println(operator.apply(7));
System.out.println(operator.apply(12));
}
}输出结果
10 14 24
示例2
import java.util.function.UnaryOperator;
public class UnaryOperatorTest2 {
public static void main(String[] args) {
UnaryOperator<Integer> operator1 = t -> t + 5;
UnaryOperator<Integer> operator2 = t -> t * 5;
// Using andThen() method int a = operator1.andThen(operator2).apply(5);
System.out.println(a);
// Using compose() method int b = operator1.compose(operator2).apply(5);
System.out.println(b);
}
}输出结果
50 30
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短