Java 8 UnaryOperator接口

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

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...