栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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();
}


总结 函数式接口,个人感觉是未来代码编写必须掌握的技能,平时可以多加查看源码和一些中间件,里面也使用了函数式接口,利用传入参数,把代码整理的简洁易懂。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/716135.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号