naryOperator 是 Java 8 函数式接口它是 Function 的特例

核心作用:接收一个参数,处理后返回 同类型 的结果。简单理解:自己变自己,类型不变 → 入参和返回值类型必须一样

一、先搞懂:它和 Function 的关系

java

运行

// UnaryOperator 源代码(继承自 Function)
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
}
  • Function<T, R> :入参 T,返回 R(类型可不同)
  • UnaryOperator :入参 T,返回 T(类型必须相同)
  • 核心方法:T apply(T t) (和 Function 一样)

一句话区分

  • 类型转换 → 用 Function
  • 只是自身运算 / 修改(类型不变)→ 用 UnaryOperator

二、最基础用法(必看)

1. 匿名内部类(老式)

java

运行

import java.util.function.UnaryOperator;

public class UnaryOperatorTest {
    public static void main(String[] args) {
        // 功能:接收整数,返回它的 2 倍(类型都是 Integer)
        UnaryOperator<Integer> uo = new UnaryOperator<Integer>() {
            @Override
            public Integer apply(Integer num) {
                return num * 2;
            }
        };

        int result = uo.apply(5);
        System.out.println(result); // 输出 10
    }
}

2. Lambda 简化(推荐)

java

运行

public class UnaryOperatorTest {
    public static void main(String[] args) {
        // 数字 → 平方(类型不变)
        UnaryOperator<Integer> square = num -> num * num;
        
        int result = square.apply(6);
        System.out.println(result); // 36
    }
}

三、常用场景:同类型运算、修改对象

示例 1:字符串处理

java

运行

// 字符串转大写(入出都是 String)
UnaryOperator<String> upper = s -> s.toUpperCase();

String result = upper.apply("hello");
System.out.println(result); // HELLO

示例 2:修改对象属性(最实用)

java

运行

class User {
    private String name;
    private int age;

    // 构造、get、set、toString
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void setAge(int age) { this.age = age; }
    @Override
    public String toString() { return name + ",年龄:" + age; }
}

java

运行

public class UnaryOperatorTest {
    public static void main(String[] args) {
        User user = new User("小明", 20);

        // 功能:年龄 +5,返回修改后的对象(类型都是 User)
        UnaryOperator<User> addAge = u -> {
            u.setAge(u.getAge() + 5);
            return u;
        };

        User newUser = addAge.apply(user);
        System.out.println(newUser); // 小明,年龄:25
    }
}

四、高级用法:链式调用(andThen /compose)

和 Function 完全一样,支持链式操作

java

运行

public class UnaryOperatorTest {
    public static void main(String[] args) {
        // f1:+2
        UnaryOperator<Integer> f1 = num -> num + 2;
        // f2:×3
        UnaryOperator<Integer> f2 = num -> num * 3;

        // andThen:先 f1,再 f2 → (5+2)*3 = 21
        UnaryOperator<Integer> chain = f1.andThen(f2);
        System.out.println(chain.apply(5)); // 21
    }
}

五、实战:通用工具方法

java

运行

public class UnaryOperatorTest {
    // 通用:处理同类型数据
    public static <T> T process(T data, UnaryOperator<T> operator) {
        return operator.apply(data);
    }

    public static void main(String[] args) {
        // 处理数字
        int num = process(10, n -> n + 10);
        System.out.println(num); // 20

        // 处理字符串
        String str = process("java", s -> s.toUpperCase());
        System.out.println(str); // JAVA
    }
}

六、扩展:BinaryOperator(两个参数)

BinaryOperator 是 BiFunction 的特例:两个入参 + 返回值,类型都相同

java

运行

import java.util.function.BinaryOperator;

public class UnaryOperatorTest {
    public static void main(String[] args) {
        // 两个 Integer → 返回 Integer(求和)
        BinaryOperator<Integer> add = (a, b) -> a + b;
        
        int sum = add.apply(10, 20);
        System.out.println(sum); // 30
    }
}

七、终极对比:四大金刚 + 两个特例

表格

接口入参返回值特点一句话
Supplier无入有出生产数据
Consumer1 个有入无出消费数据
Function1 个入出可不同类型转换
Predicate1 个boolean判断真假过滤筛选
UnaryOperator1 个入出必须相同自身运算
BinaryOperator2 个三者类型相同二元运算

八、核心总结

  1. UnaryOperator<T>入参 T,返回 T(类型一致)
  2. 继承自 Function<T, T>,是 Function 的简化版
  3. 核心方法:apply(T t)
  4. 常用场景:同类型计算、字符串处理、对象自身修改
  5. 支持链式:andThencompose

一句话记住:只做自身运算,类型不改变,首选 UnaryOperator!

本站提供的所有下载资源均来自互联网,仅提供学习交流使用,版权归原作者所有。如需商业使用,请联系原作者获得授权。 如您发现有涉嫌侵权的内容,请联系我们 邮箱:alixiixcom@163.com