lambda表达式:Java.util.function包下Bifunction,Predicate,Supplier,BinaryOperator函数式接口解析

BiFunction

引申 BiFunction 类似于Function 这里两个传入两个行为参数
在这里插入图片描述
例7BiFunction与Function默认方法的使用

public class FunctionTest2 {

    public static void main(String[] args) {
        FunctionTest2 test = new FunctionTest2();
        System.out.println(test.compose(10, x -> x * 3, y -> y * y)); //300
        System.out.println(test.compose2(10, x -> x * 3, y -> y * y)); //900

        //输入的行为的不同 返回的结果不同
        System.out.println(test.compose3(2, 3, (x, y) -> x + y));//5
        System.out.println(test.compose3(2, 3, (x, y) -> x - y));//-1
        System.out.println(test.compose3(2, 3, (x, y) -> x * y));//6
        System.out.println(test.compose3(2, 3, (x, y) -> x / y));//0

        System.out.println(test.compose4(2, 4, (x, y) -> x + y, x -> x * x));//36
    }

    public int compose(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {

        return function1.compose(function2).apply(a);
    }

    public int compose2(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {

        return function1.andThen(function2).apply(a);
    }

    public int compose3(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
        //参数怎么执行是由返回结果根据用户传过来的的行为决定
        return biFunction.apply(a, b);
    }

    public int compose4(int a, int b, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {
    	//此时调用apply()相当于当前的函数式接口的参数传值 行为就是他的实现
        return biFunction.andThen(function).apply(a, b);
    }
}

例8 BiFunction需求使用
对象

@Data
public class Person {

    private String username;

    private int age;
    }
public class PersonTest {

    public static void main(String[] args) {

        Person person1 = new Person("zhangsan", 20);
        Person person2 = new Person("lisi", 30);
        Person person3 = new Person("wangwu", 40);

        List<Person> list = Arrays.asList(person1, person2, person3);

        PersonTest test = new PersonTest();
//        List<Person> person = test.listPersonByname("zhangsan", list);
//        person.forEach(x -> System.out.println(x));
		/*
			此时行为是写死的 只能获取大于20 的List<Person> 集合
		*/
//        System.out.println(test.listPersonByAge(20, list));

        //不同行为返回的需求结果不同 具体需求是调用者决定的
        List<Person> listPerson = test.ListPersonByAge2(20, list, (x, y) -> 
        y.stream().filter(person -> person.getAge() > x).collect(Collectors.toList()));
        System.out.println(listPerson);
        System.out.println("=====================================================");
        List<Person> listPerson2 = test.ListPersonByAge2(20, list, (x, y) -> 
        y.stream().filter(person -> person.getAge() <= x).collect(Collectors.toList()));
        System.out.println(listPerson2);

    }

    public List<Person> listPersonByname(String username, List<Person> list) {
        /*
            将List转换成流 流里每个对象都是Person对象 判断为true的流收集返回
         */
        return list.stream().filter(x -> username.equals(x.getUsername()))
                .collect(Collectors.toList());
    }

    public List<Person> listPersonByAge(Integer age, List<Person> list) {
        //{}写带返回结果的语句,需 加上return不然会报错
        BiFunction<Integer, List<Person>, List<Person>> biFunction = (x, y) ->
                y.stream().filter(person -> person.getAge() > age).collect(Collectors.toList());
        return biFunction.apply(age, list);
    }

    public List<Person> listPersonByAge2(Integer age, List<Person> personList, BiFunction<Integer, List<Person>, List<Person>> biFunction) {
        return biFunction.apply(age, personList);
    }

}

Predicate

在这里插入图片描述
在这里插入图片描述

public class PredicateTest {

    public static void main(String[] args) {
		/*
			常用做过滤 就是根据行为动作去返回为true的值 filter接口行为参数就是该函数式接口
		*/
        Predicate<String> predicate = x -> x.length() > 5;
        System.out.println(predicate.test("nihaoa")); //true

    }
}

Predicate接口默认方法

	/**
		当前Predicate 行为test结果 与 传入行为 test结果都为true时为true 
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
   		返回当前Predicate 行为test的结果取反
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
		 当前Predicate 行为test结果 与 传入行为 test结果有一个为true时为true 
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
   		静态方法 类似equals 判断两个参数是否相等
   		System.out.println(Predicate.isEqual("22").test("22"));//true
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }

例:Predicate默认方法和静态方法使用

public class PredicateTest2 {

    public static void main(String[] args) {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        /**
         * 与传统相比更加灵活 传统编程下需要写5个对应的方法
         */
        PredicateTest2 predicateTest2 = new PredicateTest2();
        predicateTest2.conditionFilter(list, x -> x % 2 == 0);
        System.out.println("=====================");
        predicateTest2.conditionFilter(list, x -> x % 2 != 0);
        System.out.println("=====================");
        predicateTest2.conditionFilter(list, x -> x % x > 2);
        System.out.println("=====================");
        predicateTest2.conditionFilter(list, x -> true); //返回所有的
        System.out.println("=====================");
        predicateTest2.conditionFilter(list, x -> false); //所有的都不返回
        System.out.println("=====================");

        /*
            例:找出集合中大于5并且是偶数的数字
         */
        predicateTest2.conditionFilter2(list, x -> x > 5, x -> x % 2 == 0); //6 8 10


        predicateTest2.conditionFilter3(list, x -> x > 5, x -> x % 2 == 0); // 与上面的相反
        System.out.println("============================");
//        System.out.println(Predicate.isEqual(22).and(x -> (int)x / 22 == 1).test("22"));//false
        System.out.println(Predicate.isEqual(new Date()).test(new Date()));//false

    }


    public void conditionFilter(List<Integer> list, Predicate<Integer> predicate) {

        list.forEach(x -> {
            if (predicate.test(x)) {
                System.out.println(x);
            }
        });
    }

    public void conditionFilter2(List<Integer> list, Predicate<Integer> predicate, Predicate<Integer> integerPredicate) {
        list.forEach(x -> {
            if (predicate.and(integerPredicate).test(x)) {
                System.out.println(x);
            }
        });


    }

    public void conditionFilter3(List<Integer> list, Predicate<Integer> predicate, Predicate<Integer> integerPredicate) {
        list.forEach(x -> {
            if (predicate.and(integerPredicate).negate().test(x)) {
                System.out.println(x);
            }
        });
    }
    
}

Supplier

doc
表示结果的提供者。不要求每次被调用时返回新的或不同的结果。

  • 常用与无参的工厂返回实例 与function相反

在这里插入图片描述

public class SupplierTest {

    public static void main(String[] args) {

        Supplier supplier = () -> "nihaoa";
        System.out.println(supplier.get());//nihaoa

    }
}


新增实体类

public class Student {

    private String username = "zhangsan";

    private int age = 20;

    public Student() {
    }

    public Student(String username) {
        this.username = username;
    }

    public String getUsername() {
        return username;
    }

    public int getAge() {
        return age;
    }
}

public class StudentTest {

    public static void main(String[] args) {

        //传统拿出Student数据需要
        Student student = new Student();
        System.out.println(student.getUsername());

        //lambda表达式
        Supplier<String> supplier = () -> new Student().getUsername();
        System.out.println(supplier.get());
        System.out.println("==================================");
        /*
            构造方法引用  不接收参数返回 Student对象
            new 直接指向对象的无参构造方法
         */
        Supplier<Student> supplier2 = Student::new;
        System.out.println(supplier2.get().getUsername());
    }
}

BinaryOperator

doc文档
表示对同一类型的两个参数执行的操作,产生与参数相同类型的结果。对于操作数和结果都是同一类型的情况,这是双函数的一种特例。
这是一个函数接口 extends BiFunction函数接口,其函数方法是apply(Object,Object)。

在这里插入图片描述

**例 BinaryOperator函数接口方法实例 **

public static void main(String[] args) {

        /*
             用来计算相类的的加减乘除运算会变得简单 我们可以理解为将方法变成参数
         */
        BinaryOperator<Integer> binaryOperator = (x, y) -> x + y;

        System.out.println(binaryOperator.apply(10, 9));//19
        System.out.println("===");

        BinaryOperatorTest binaryOperatorTest = new BinaryOperatorTest();

        System.out.println(binaryOperatorTest.operation(10, 20, (x, y) -> x + y));
        System.out.println("===");
        System.out.println(binaryOperatorTest.operation(10, 20, (x, y) -> x - y));
        System.out.println("===");
        System.out.println(binaryOperatorTest.operation(10, 20, (x, y) -> x * y));
        System.out.println("===");
        System.out.println(binaryOperatorTest.operation(10, 20, (x, y) -> x / y));
        System.out.println("===");

        /*
            将参数(2, 9)通过comparable 行为得到的结果 是否大于 0 true 输出2 否则 输出 9
         */
        Comparator<Integer> comparator = (x, y) -> x * y;
        System.out.println(BinaryOperator.maxBy(comparator).apply(2, 9));
}



/*
19
===
30
===
-10
===
200
===
0
===
 */

BinaryOperator静态方法

	 /*
		传入comparator 行为 执行compare(a, b)参数得到结果 结果<=0 输出 参数a 否则 输出 参数b
		Comparator传入两个参数 通过行为得到的结果 去和0比较 得到 a和b的大小
     */
    public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
    }

    /*
    	相反
   		传入comparator 行为 执行compare(a, b)参数得到结果 结果>=0 输出 参数a 否则 输出 参数b
     */
    public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
    }

例 BinaryOperator函数静态方法实例

public class BinaryOperatorTest {

    public static void main(String[] args) {
        /*
            自定义
            得到最小的字符?
         */
        //length长度下
        System.out.println(binaryOperatorTest.getShort("hello", "sout", (x, y) -> x.length() - y.length()));//sout
        //首字母排前面的小
        System.out.println(binaryOperatorTest.getShort("hello", "sout", (x, y) -> x.charAt(0) - y.charAt(0)));//hello
    }

    public String getShort(String a, String b, Comparator<String> comparator) {

        return BinaryOperator.minBy(comparator).apply(a, b);
    }
}

Comparator比较器

	传入两个值 返回一个int值 常用与两个参数判断 正数大 负数小
 int compare(T o1, T o2)

Comparable比较器

	传入一个值 返回一个int值  正数大 负数小
    public int compareTo(T o);
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值