Java8 函数式接口Predicate、Consumer、Function、Supplier

Java8 函数式接口Predicate、Consumer、Function、Supplier,第1张

Java8 函数式接口Predicate、Consumer、Function、Supplier

文章目录

前言一、Predicate

1. boolean test(T var1);2. and(Predicate other)3. negate()4. or(Predicate other)5. isEqual(Object targetRef) 二、Consumer

1. accept(T var1)2. andThen(Consumer after) 三、Function

1. apply(T var1)2. compose(Function before)3. andThen(Function after)4. identity() 四、Supplier

1. get 总结


前言

Java8是 Java 语言的一个重要版本,该版本于2014年3月发布,是自Java5以来最具革命性的版 本,这个版本包含语言、编译器、库、工具和JVM等方面的十多个新特性。


提示:以下是本篇文章正文内容,下面案例可供参考

一、Predicate

Predicate

@FunctionalInterface
public interface Predicate {
	// 用来处理参数T,判断是否符合条件
    boolean test(T var1);
	// 可理解为 条件A && 条件B
    default Predicate and(Predicate other) {
        Objects.requireNonNull(other);
        return (t) -> {
            return this.test(t) && other.test(t);
        };
    }
	// 对当前判断进行"!" *** 作,即取非 *** 作,可理解为 ! 条件A
    default Predicate negate() {
        return (t) -> {
            return !this.test(t);
        };
    }
	// 对当前判断进行"||" *** 作,即取或 *** 作,可以理解为 条件A ||条件B
    default Predicate or(Predicate other) {
        Objects.requireNonNull(other);
        return (t) -> {
            return this.test(t) || other.test(t);
        };
    }
	// 对当前 *** 作进行"=" *** 作,即取等 *** 作,可以理解为 A == B
    static  Predicate isEqual(Object targetRef) {
        return null == targetRef ? Objects::isNull : (object) -> {
            return targetRef.equals(object);
        };
    }

    static  Predicate not(Predicate target) {
        Objects.requireNonNull(target);
        return target.negate();
    }
}
1. boolean test(T var1);

代码如下(示例):

 Predicate predicate = x -> x >  0;
 System.out.println(predicate.test(10));//true
2. and(Predicate other)

代码如下(示例):

Predicate predicate = x -> x >100;
predicate = predicate.and(x -> x % 2 == 0 );
System.out.println(predicate.test(98));// false
System.out.println(predicate.test(102));// true
System.out.println(predicate.test(103));// false
3. negate()

代码如下(示例):

Predicate personPredicate = x -> x.age > 22;
System.out.println(
                Stream.of(
                        new Person(21,"zhangsan"),
                        new Person(22,"lisi"),
                        new Person(23,"wangwu"),
                        new Person(24,"wangwu"),
                        new Person(25,"lisi"),
                        new Person(26,"zhangsan")
                )
                        .filter(personPredicate.negate())
                        .count()
        );// 4
4. or(Predicate other)

代码如下(示例):

 Predicate predicate =  x -> x.name.equals("lisi");
 predicate = predicate.or(x -> x.age > 25);
 System.out.println(
                Stream.of(
                        new Person(21,"zhangsan"),
                        new Person(22,"lisi"),
                        new Person(23,"wangwu"),
                        new Person(24,"wangwu"),
                        new Person(25,"lisi"),
                        new Person(26,"zhangsan")
                )
                        .filter(predicate)
                        .count()
        );
5. isEqual(Object targetRef)

代码如下(示例):

Person person = new Person(22,"lisi");
Predicate predicate =  Predicate.isEqual(person);
System.out.println(
                Stream.of(
                        new Person(21,"zhangsan"),
                        new Person(22,"lisi"),
                        new Person(23,"wangwu"),
                        new Person(24,"wangwu"),
                        new Person(22,"lisi"),
                        new Person(26,"zhangsan")
                )
                        .filter(predicate)
                        .count()
        );// 2
二、Consumer

Consumer 数据获取

@FunctionalInterface
public interface Consumer {
    void accept(T var1);

    default Consumer andThen(Consumer after) {
        Objects.requireNonNull(after);
        return (t) -> {
            this.accept(t);
            after.accept(t);
        };
    }
}

1. accept(T var1)

代码如下(示例):

List lisiList = new ArrayList<>();
Consumer  consumer  =  x -> {
    if (x.name.equals("lisi")){
        lisiList.add(x);
    }
};
Stream.of(
        new Person(21,"zhangsan"),
        new Person(22,"lisi"),
        new Person(23,"wangwu"),
        new Person(24,"wangwu"),
        new Person(23,"lisi"),
        new Person(26,"lisi"),
        new Person(26,"zhangsan")
).forEach(consumer);

System.out.println(JSON.toJSONString(lisiList));
2. andThen(Consumer after)

代码如下(示例):

List lisiList = new ArrayList<>();
Consumer  consumer  =  x -> {
    if (x.name.equals("lisi")){
        lisiList.add(x);
    }
};

consumer = consumer.andThen(
   x -> lisiList.removeIf(y -> y.age < 23)
);

Stream.of(
        new Person(21,"zhangsan"),
        new Person(22,"lisi"),
        new Person(23,"wangwu"),
        new Person(24,"wangwu"),
        new Person(23,"lisi"),
        new Person(26,"lisi"),
        new Person(26,"zhangsan")
).forEach(consumer);

System.out.println(JSON.toJSONString(lisiList));
三、Function

Function 类型转换

@FunctionalInterface
public interface Function {
    R apply(T var1);
	//将Function对象应用到输入的参数上,然后返回计算结果。
    default  Function compose(Function before) {
        Objects.requireNonNull(before);
        return (v) -> {
            return this.apply(before.apply(v));
        };
    }
	//返回一个先执行当前函数对象apply方法再执行after函数对象apply方法的函数对象。
    default  Function andThen(Function after) {
        Objects.requireNonNull(after);
        return (t) -> {
            return after.apply(this.apply(t));
        };
    }
	//返回一个先执行before函数对象apply方法再执行当前函数对象apply方法的函数对象
    static  Function identity() {
        return (t) -> {
            return t;
        };
    }
}

1. apply(T var1)

代码如下(示例):

Function name = e -> e * 2;
int value = name.apply(3);
System.out.println("andThen value=" + value);// 6
2. compose(Function before)

代码如下(示例):

Function name = e -> e * 2;
Function square = e -> e * e;
// 运算逻辑 andThen 先计算前边的,再把得到的参数传入下一次计算
int value = name.andThen(square).apply(3);
System.out.println("andThen value=" + value);// 36
3. andThen(Function after)

代码如下(示例):

Function name = e -> e * 2;
Function square = e -> e * e;
// compose 先计算后边的逻辑,再把参数传入前边的运算
int value2 = name.compose(square).apply(3);
System.out.println("compose value2=" + value2);// 18
4. identity()

代码如下(示例):

Function name = e -> e * 2;
Function square = e -> e * e;
Object identity = Function.identity().apply("huohuo");
System.out.println(identity);// huohuo
四、Supplier

Supplier 获取数值

1. get
@FunctionalInterface
public interface Supplier {
    T get();
}

代码如下(示例):

public static void main(String[] args) {
    int[] numbers = {100, 200, 300, 400, 500, -600, -700, -800, -900, -1000};
    int numberMax = arrayMax(
            () -> {
                int max = numbers[0];
                for (int number : numbers) {
                    if (max < number) {
                        max = number;
                    }
                }
                return max;
            }
    );
    System.out.println("数组中的最大值为:" + numberMax);
}

public static Integer arrayMax(Supplier s){
    return s.get();
}


总结 函数式接口,个人感觉是未来代码编写必须掌握的技能,平时可以多加查看源码和一些中间件,里面也使用了函数式接口,利用传入参数,把代码整理的简洁易懂。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/zaji/5712774.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存