Fork me on GitHub

Java Lambda表达式

Java的方法分为实例方法,以及静态方法。它们本质上都相当于过程式语言的函数,但Java的实例方法隐含了个参数this

我们常把支持函数式编程风格称为Lambda表达式。

 

匿名类方式编写:

InnerClass ic = new InnerClass() {
    public int method(String s1, String s2) {
        return s1.equals(s2);
    }
});

 

Lambd表达式方式:

InnerClass ic =(s1, s2) -> {
    return s1.equals(s2);
 }

 

如果只有一行return代码,则可更简:

InnerClass ic=(s1, s2) ->s1.equals(s2)

 

只定义了单方法的接口为FunctionalInterface,用@FunctionalInterface标记。

Lambda表达式可不写FunctionalInterface实现类,而简化。

 

如果某个方法签名(除了方法名外,参数、返回类型相同则称方法签名一致)和接口一致,可直接传入方法引用。

@FunctionalInterface
public interface Comparator<T> {

    int compare(T o1, T o2);

    boolean equals(Object obj);

    default Comparator<T> reversed() {
        return Collections.reverseOrder(this);
    }
}

public class Main {
    public static void main(String[] args) {
        String[] array = new String[] { "Avocado", "Cappuccino","Espresso"};
        Arrays.sort(array, Main::cmp); //某个方法签名和接口恰好一致,就可以直接传入方法引用。
/*
*sort(T[] a, Comparator<? super T> c) Sorts the specified array of objects according to the order induced by the specified comparator.
*/

/*Sorting an array of Objects using a Comparator,
*Besides using the Comparable implementation approach, 
*it’s also possible to sort an array of Objects by passing an implementation of 
*the java.util.Comparator interface to the Arrays.sort() method*/
/*
*An array class is a class containing static methods that are used with arrays in order to 
search, sort, compare, inserting elements, or returning a string representation of an array. in an array. 
So let us specify the functions first and later onwards we will be discussing the same. 
They are as follows been present in java.util.Arrays class. 
Here we will be discussing out different plots using the sort() method of the Arrays class.
*/
/*
*Arrays.sort() method consists of two variations 
*one in which we do not pass any arguments where it sort down the complete array be it integer array or character array 
*but if we are supposed to sort a specific part using this method of Arrays class then we overload it and pass the starting and last index to the array.
* /
/*
*‘be it……ro……’ is s an archaic construction, inverting the verb and the subject, 
*and using the (nearly obsolete) subjunctive form of the verb, to convey a conditional.
*It survives much more in the past (where, apart from were, the subjunctive is the same as the ordinary past). So:
*Had I known ... = If I had known ...
*Had he seen it, ... = If he had seen it, ...
*Should you want me, ... = If you should want me, ... = If you wanted me, ...
*Were I to say that, ... = If I were to say that, ... = If I said that, ...
*These past forms are all somewhat literary, but occasionally used even in speech.
*The following present forms are even more literary, and rarely used except to be deliberately old-fashioned:
*Be he good or evil, ... = Whether he is good or evil, 
*...Be it so or not, ... = Whether it is so or not, ...*/



        System.out.println(String.join(", ", array));
    }

    static int cmp(String s1, String s2) {
        return s1.compareTo(s2);
    }
}

 

引用实例方法

public class Main {
    public static void main(String[] args) {
        String[] array = new String[] { "Avocado", "Cappuccino","Espresso"};
        Arrays.sort(array, String::compareTo);//签名只有一个参数,能和int Comparator<String>.compare(String, String)匹配是因为第一个隐含参数总是传入this,相当于静态方法。实例类型被看作第一个参数类型。
        System.out.println(String.join(", ", array));
    }
}

 

 

构造方法引用

//传统做法
//ArrayList creates an array of objects where the array can grow dynamically.
//List interface creates a collection of elements that are stored in a sequence and they are identified and accessed using the index.
//List interface is implemented by the classes of ArrayList.
class Person {
    String name;
    public Person(String name) {
        this.name = name;
    }
}
List<String> names = List.of("Bob", "Alice", "Tim");
List<Person> persons = new ArrayList<>();
for (String name : names) {
    persons.add(new Person(name));
}
//The List.of() static factory methods provide a convenient way to create immutable lists. 

 

 

// 引用构造方法
//构造方法的引用写法是 类名::new
//List interface creates a collection of elements that are stored in a sequence and they are identified and accessed using the index.
//ArrayList creates an array of objects where the array can grow dynamically.
// List interface is implemented by the classes of ArrayList.

public class Main {
    public static void main(String[] args) {
        List<String> names = List.of("Bob", "Alice", "Tim");
        List<Person> persons = names.stream().map(Person::new).collect(Collectors.toList());
        System.out.println(persons);
    }
}

class Person {
    String name;
    public Person(String name) {
        this.name = name;
    }
    public String toString() {
        return "Person:" + this.name;
    }
}

 

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
}
//map()需要传入的FunctionalInterface的定义

 

泛型对应上就是方法签名Person apply(String),构造方法会隐式地返回this实例。实例类型被看作返回类型。

 

posted @ 2022-02-08 17:58  z_s_s  阅读(61)  评论(0)    收藏  举报