Operator接口表示传入的参数类型和返回值类型一致,分为一元操作和二元操作两种,BinaryOperator、UnaryOperator 。
目录
-
UnaryOperator
UnaryOperator是一元操作接口,也就是只能接收一个参数。UnaryOperator继承了Function接口。所以在操作上可以使用Function中的方法。@FunctionalInterface public interface UnaryOperator<T> extends Function<T, T> { /** * Returns a unary operator that always returns its input argument. * * @param <T> the type of the input and output of the operator * @return a unary operator that always returns its input argument */ static <T> UnaryOperator<T> identity() { return t -> t; } }
代码示例
public class TestUnaryOperator { public static void main(String[] args) { test(100, val -> val * 5); testAndThen1("test", str -> str.replaceAll("t", " operator "), a -> a.toUpperCase()); testAndThen2("test UnaryOperator of andThen", obj -> obj.toUpperCase(), str -> str.contains("UnaryOperator")); testCompose(new User("张三", 33, "北京市朝阳区"), User::getAddress, str -> { if (str.contains("北京市")) { return str; } else if (str.contains("上海市")) { return "外地"; } else { return "未知"; } }); } // 测试apply方法 public static void test(int val, UnaryOperator<Integer> operator) { Integer apply = operator.apply(val); System.out.println(apply); } // 测试andThen方法,注意传参 public static void testAndThen1(String val, UnaryOperator<String> operator, U