Java JDK 1.8 新特性 常用函数式接口 Supplier Consumer Function Predicate

Supplier

返回一个指定泛型的数据,不需要传入值

@FunctionalInterface
public interface Supplier<T> {
    T get();
}

// 使用案例 supplier方法使用
public class TestSupplier {
    public static void main(String[] args) {
        printMax(() -> {
            int[] arr = {1, 3, 4, 6};
            Arrays.sort(arr); // 升序排序
            return arr[arr.length - 1];
        });
    }

    public static void printMax(Supplier<Integer> supplier) {
        int max = supplier.get();
        System.out.println("max: " + max);
    }
}
Consumer

拿到指定泛型的数据进行处理,不需要返回值

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
    
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

// 使用案例1 accept方法使用
public class TestConsumer {
    public static void main(String[] args) {
        printUpper((String str) -> {
            System.out.println("upper str: " + str.toUpperCase()); // 打印 "TEST"
        });
    }

    public static void printUpper(Consumer<String> consumer) {
        consumer.accept("test");
    }
}

// 使用案例2 andThen方法使用
public class TestConsumer {
        public static void main(String[] args) {
        printUpperAndLower((Integer sum) -> {
            ++sum;
            System.out.println("sum: " + sum); // 打印 "11"
        },(Integer sum) -> {
            ++sum;
            System.out.println("sum: " + sum); // 打印 "11"
        });
    }

    public static void printUpperAndLower(Consumer<Integer> consumer1, Consumer<Integer> consumer2) {
        Integer sum = 10;
        consumer1.accept(sum);
        consumer2.accept(sum);
        // andThen方法相当于上述两行代码
        consumer1.andThen(consumer2).accept(sum);
    }
}

Function

将传进来的T类型转换为R类型并返回

@FunctionalInterface
public interface Function<T, R> {
    
    R apply(T t);

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

// 使用案例1 apply方法使用
public class TestFunction {
    public static void main(String[] args) {
        changType((Integer sum) -> {
            return sum + "s";
        });
    }

    public static void changType(Function<Integer, String> func) {
        String s = func.apply(10);
        System.out.println(s); // 打印 ”10s“
    }
}

// 使用案例2 andThen方法使用
public class TestFunction {
	public static void main(String[] args) {
        changType((Integer sum) -> {
            return sum + "s";
        },(String sum) -> {
            return sum + "q";
        });
    }
	// 注意两个Function参数类型与案例1不同
	public static void changType(Function<Integer, String> func1, Function<String, String> func2) {
    
    	String s1 = func1.apply(10); // s1 = ”10s“
    	String s2 = func2.apply(s1); // s2 = ”10qs“
    	// andThen方法等效于上述两行代码
    	String s = func1.andThen(func2).apply(10); // s = ”10qs“
	}
}
Predicate

该接口用于对数据进行判断,得到boolean类型结果

@FunctionalInterface
public interface Predicate<T> {

    boolean test(T t);

    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }

    @SuppressWarnings("unchecked")
    static <T> Predicate<T> not(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>)target.negate();
    }
}

// 使用案例1 test方法使用
public class TestPredicate {
    public static void main(String[] args) {
        isTomOrNot((String name) -> {
            if("Tom".equals(name)){
                return true;
            } else {
                return false;
            }
        });
    }

    public static void isTomOrNot(Predicate<String> predicate) {
        boolean jerry = predicate.test("Jerry");
        System.out.println(jerry); // false
        boolean tom = predicate.test("Tom");
        System.out.println(tom);// true
    }
}

// 使用案例2 and or negate方法使用
public class TestPredicate {
    public static void main(String[] args) {
        isTomOrNot((String name) -> {
            return name.contains("T"); // 字符串中包含 "T"
        }, (String name) -> {
            return name.contains("o"); // 字符串中包含 "o"
        });
    }

    public static void isTomOrNot(Predicate<String> predicate1, Predicate<String> predicate2) {
        boolean tom1 = predicate1.test("Tom");
        boolean tom2 = predicate2.test("Tom");

        // and 表示两个test结果的相&& 等效于tom1 && tom2
        boolean bool1 = predicate1.and(predicate2).test("Tom");
        if(bool1){
            System.out.println("既包含T也包含o");
        }

        boolean tom3 = predicate1.test("Tem");
        boolean tom4 = predicate2.test("Tem");
        // and 表示两个test结果的相|| 等效于tom3 || tom4
        boolean bool2 = predicate1.or(predicate2).test("Tem");
        if(bool2){
            System.out.println("包含T或包含o");
        }

        // negate相当于对结果进行取反
        boolean b = predicate1.negate().test("Jerry");
        if(b){
            System.out.println("不包含T之后取反");
        }

    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值