了不起的Java-Lambda函数式接口和方法引用

问题引入

有一个简单的java类Apple,需要对List实例进行筛选,比如选出“红苹果”、“绿苹果”、“重苹果”、“又红又重的苹果”,你会怎么做?

相关类和数据

public static class Apple {
        private int weight = 0;
        private String color = "";

        public Apple(int weight, String color){
            this.weight = weight;
            this.color = color;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
        }

        public String toString() {
            return "Apple{" +
                   "color='" + color + '\'' +
                   ", weight=" + weight +
                   '}';
        }
    }

数据:

List<Apple> inventory = Arrays.asList(new Apple(80,"green"),
new Apple(155, "green"),
new Apple(120, "red"),
new Apple(230, "red"));

传统式编程

一般会想到用for + if 进行遍历筛选,过滤器函数具体做法:

//红苹果
    public static List<Apple> filterRedApples(List<Apple> inventory){
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory){
            if ("red".equals(apple.getColor())) {
                result.add(apple);
            }
        }
        return result;
    }
    
    //绿苹果
    public static List<Apple> filterGreenApples(List<Apple> inventory){
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory){
            if ("green".equals(apple.getColor())) {
                result.add(apple);
            }
        }
        return result;
    }
    
    //重苹果
    public static List<Apple> filterHeavyApples(List<Apple> inventory){
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory){
            if (apple.getWeight() > 150) {
                result.add(apple);
            }
        }
        return result;
    }

    //又红又重的苹果
    public static List<Apple> filterHeavyRedApples(List<Apple> inventory){
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory){
            if (apple.getWeight() > 150 && "red".equals(apple.getColor())) {
                result.add(apple);
            }
        }
        return result;
    }

 

调用:

        List<Apple> greenApplesOld = filterGreenApples(inventory);
        System.out.println(greenApplesOld);

        List<Apple> redHeavyApplesOld = filterHeavyRedApples(inventory);
        System.out.println(redHeavyApplesOld);

输出:

[Apple{color='green', weight=80}, Apple{color='green', weight=155}]
[Apple{color='red', weight=230}]

有几个条件就写几个方法,反正for+if比较容易,大家都爱这么干。但这种重复的粘贴复制真的好吗?

匿名类

忘记它吧,只比传统方式好一点点。

谓词Predicate(通过Lambda表达式)

其实Predicate简单来说就是具有布尔返回的泛型函数接口。函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。
函数式接口可以被隐式转换为 lambda 表达式。和我们熟悉的“策略设计模式”的思路比较像。

Predicate定义:

@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);
}
......
}

 

其中test用于输入T类型,输出验证布尔返回。
我们将过滤器函数增加一个参数,这个参数就是函数接口(就是谓词Predicate)

    public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p){
        List<Apple> result = new ArrayList<>();
        for(Apple apple : inventory){
            if(p.test(apple)){
                result.add(apple);
            }
        }
        return result;
    } 


在过滤红色、绿色、重的红色之类的列表时,不用再单独新建方法,在运行时代入即可

        // 谓词方式
        // [Apple{color='green', weight=80}, Apple{color='green', weight=155}]
        List<Apple> greenApples2 = filterApples(inventory, (Apple a) -> "green".equals(a.getColor()));
        System.out.println(greenApples2);
        
        // [Apple{color='green', weight=155}]
        List<Apple> heavyApples2 = filterApples(inventory, (Apple a) -> a.getWeight() > 150);
        System.out.println(heavyApples2);
//复合谓词的用法,又红又重的苹果
Predicate<Apple> p = (Apple a) -> a.getWeight() > 150;
p = p.and((Apple a) -> "red".equals(a.getColor()));
List<Apple> heavyRedApples2 = filterApples(inventory, p);
System.out.println(heavyRedApples2);

其中,复合谓词使用了and,除此之外,还有negate(取反)、or(或),注意,如果是a.or(b).and(c),那如果解释成括号用法,即(a || b) && c

方法引用

java8引入了双冒号,用于方法引用。
方法引用通过方法的名字来指向一个方法。
方法引用可以使语言的构造更紧凑简洁,减少冗余代码。
方法引用使用一对冒号 :: 。

如果在这个过滤器的例子中,需要新建过滤判断方法

    public static boolean isGreenApple(Apple apple) {
        return "green".equals(apple.getColor()); 
    }

    public static boolean isHeavyApple(Apple apple) {
        return apple.getWeight() > 150;
    }

 

在使用的时候,传入方法名即可,其中filterApples方法继续沿用上例的方法,第二个参数实际是一个谓词函数接口Predicate,
双冒号组成的部分看起来比直接的Lambda表达式要简短

对比一下:

  • filterApples(inventory, (Apple a) -> "green".equals(a.getColor()));
  • filterApples(inventory, FilteringApples::isGreenApple);

方法引用更加直观,他将方法当做参数来引用,所以就叫做“方法引用”,该方法的输入类型(Apple),输出类型(boolean)和Predicate参数是一致的

// 方法引用 
// [Apple{color='green', weight=80}, Apple{color='green', weight=155}]
List<Apple> greenApples = filterApples(inventory, FilteringApples::isGreenApple);
System.out.println(greenApples);

// [Apple{color='green', weight=155}]
List<Apple> heavyApples = filterApples(inventory, FilteringApples::isHeavyApple);
System.out.println(heavyApples);

 

常见的函数式接口

除了谓词函数接口Predicate,还有很多函数式接口

JDK 1.8 之前已有的函数式接口:

  • java.lang.Runnable
  • java.util.concurrent.Callable
  • java.security.PrivilegedAction
  • java.util.Comparator
  • java.io.FileFilter
  • java.nio.file.PathMatcher
  • java.lang.reflect.InvocationHandler
  • java.beans.PropertyChangeListener
  • java.awt.event.ActionListener
  • javax.swing.event.ChangeListener

JDK 1.8 新增加的函数接口:

  • java.util.function

java.util.function 它包含了很多类,用来支持 Java的 函数式编程,该包中的函数式接口有:

序号接口 & 描述
1BiConsumer<T,U>

代表了一个接受两个输入参数的操作,并且不返回任何结果

2BiFunction<T,U,R>

代表了一个接受两个输入参数的方法,并且返回一个结果

3BinaryOperator<T>

代表了一个作用于于两个同类型操作符的操作,并且返回了操作符同类型的结果

4BiPredicate<T,U>

代表了一个两个参数的boolean值方法

5BooleanSupplier

代表了boolean值结果的提供方

6Consumer<T>

代表了接受一个输入参数并且无返回的操作

7DoubleBinaryOperator

代表了作用于两个double值操作符的操作,并且返回了一个double值的结果。

8DoubleConsumer

代表一个接受double值参数的操作,并且不返回结果。

9DoubleFunction<R>

代表接受一个double值参数的方法,并且返回结果

10DoublePredicate

代表一个拥有double值参数的boolean值方法

11DoubleSupplier

代表一个double值结构的提供方

12DoubleToIntFunction

接受一个double类型输入,返回一个int类型结果。

13DoubleToLongFunction

接受一个double类型输入,返回一个long类型结果

14DoubleUnaryOperator

接受一个参数同为类型double,返回值类型也为double 。

15Function<T,R>

接受一个输入参数,返回一个结果。

16IntBinaryOperator

接受两个参数同为类型int,返回值类型也为int 。

17IntConsumer

接受一个int类型的输入参数,无返回值 。

18IntFunction<R>

接受一个int类型输入参数,返回一个结果 。

19IntPredicate

:接受一个int输入参数,返回一个布尔值的结果。

20IntSupplier

无参数,返回一个int类型结果。

21IntToDoubleFunction

接受一个int类型输入,返回一个double类型结果 。

22IntToLongFunction

接受一个int类型输入,返回一个long类型结果。

23IntUnaryOperator

接受一个参数同为类型int,返回值类型也为int 。

24LongBinaryOperator

接受两个参数同为类型long,返回值类型也为long。

25LongConsumer

接受一个long类型的输入参数,无返回值。

26LongFunction<R>

接受一个long类型输入参数,返回一个结果。

27LongPredicate

R接受一个long输入参数,返回一个布尔值类型结果。

28LongSupplier

无参数,返回一个结果long类型的值。

29LongToDoubleFunction

接受一个long类型输入,返回一个double类型结果。

30LongToIntFunction

接受一个long类型输入,返回一个int类型结果。

31LongUnaryOperator

接受一个参数同为类型long,返回值类型也为long。

32ObjDoubleConsumer<T>

接受一个object类型和一个double类型的输入参数,无返回值。

33ObjIntConsumer<T>

接受一个object类型和一个int类型的输入参数,无返回值。

34ObjLongConsumer<T>

接受一个object类型和一个long类型的输入参数,无返回值。

35Predicate<T>

接受一个输入参数,返回一个布尔值结果。

36Supplier<T>

无参数,返回一个结果。

37ToDoubleBiFunction<T,U>

接受两个输入参数,返回一个double类型结果

38ToDoubleFunction<T>

接受一个输入参数,返回一个double类型结果

39ToIntBiFunction<T,U>

接受两个输入参数,返回一个int类型结果。

40ToIntFunction<T>

接受一个输入参数,返回一个int类型结果。

41ToLongBiFunction<T,U>

接受两个输入参数,返回一个long类型结果。

42ToLongFunction<T>

接受一个输入参数,返回一个long类型结果。

43UnaryOperator<T>

接受一个参数为类型T,返回值类型也为T。


函数式接口实例

Predicate

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateFunctionExample {
    public static void main(String args[]) {
        Predicate<Integer> positive = i -> i > 0;
        List<Integer> integerList = Arrays.asList(new Integer(1), new Integer(10), new Integer(200), new Integer(101),
                new Integer(-10), new Integer(0));
        List<Integer> filteredList = filterList(integerList, positive);
        filteredList.forEach(System.out::println);
    }

    public static List<Integer> filterList(List<Integer> listOfIntegers, Predicate<Integer> predicate) {
        List<Integer> filteredList = new ArrayList<Integer>();
        for (Integer integer : listOfIntegers) {
            if (predicate.test(integer)) {
                filteredList.add(integer);
            }
        }
        return filteredList;
    }
}

 

Consumer

定义:

@FunctionalInterface
public interface Consumer<T> {

    void accept(T t);

例子:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerFunctionExample {
    public static void main(String args[]) {
        Consumer<Integer> consumer = i -> System.out.print(" " + i);
        List<Integer> integerList = Arrays.asList(new Integer(1), new Integer(10), new Integer(200), new Integer(101),
                new Integer(-10), new Integer(0));
        printList(integerList, consumer);
    }

    public static void printList(List<Integer> listOfIntegers, Consumer<Integer> consumer) {
        for (Integer integer : listOfIntegers) {
            consumer.accept(integer);
        }
    }
}

注意,返回是void,只管执行,不用输出,如果需要输入怎么办,请看下面。

Function

定义:

@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;
    }
}

例子:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class FunctionExample{ public static void main(String args[]){ Function<Employee, String> funcEmpToString= (Employee e)-> {return e.getName();}; List<Employee> employeeList= Arrays.asList(new Employee("Tom Jones", 45), new Employee("Harry Major", 25), new Employee("Ethan Hardy", 65), new Employee("Nancy Smith", 15), new Employee("Deborah Sprightly", 29)); List<String> empNameList=convertEmpListToNamesList(employeeList, funcEmpToString); empNameList.forEach(System.out::println); } public static List<String> convertEmpListToNamesList(List<Employee> employeeList, Function<Employee, String> funcEmpToString){ List<String> empNameList=new ArrayList<String>(); for(Employee emp:employeeList){ empNameList.add(funcEmpToString.apply(emp)); } return empNameList; } }

还有一些不大常用到的

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值