Method References trong java

Ở bài trước chúng ta đã thấy sự lợi hại lambda expression, nó đã giúp code tụi mình ngắn và đẹp hơn lắm đúng không nào? Nhưng đôi lúc lambda expression còn có thể rút gọn hơn nữa đấy!!!

Đôi lúc lambda expression chỉ gọi một method có sẵn của một class, nếu chúng ta sử dụng lambda expression cũng ok không sao, nhưng mà xem hay xem qua method references thử nha, với method reference ta chỉ cần cái tên thôi =)). 

Mình lấy lại của lambda expression trước, chúng ta có  

public class Student {
    private String name;
    private int age;
    private String sex;
    private int score;

    public Student(String name, int age, String sex, int score) {
        this.name = name;
        this.age = age;
        this.sex = sex;
        this.score = score;
    }

    public void print() {
        System.out.println(this.name + " " + this.age + " " + this.sex + " " + this.score);
    }

    public static int compareByAge(Student a, Student b) {
        return a.getAge() - b.getAge();
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }
}

Mình đã thêm function compareByAge() để so sánh tuổi của 2 học sinh trong class Student.

VD1: Sắp xếp các học sinh chứa trong danh sách students theo tuổi tăng dần bằng cách sử dụng hàm sort của Collections cung cấp sẵn.

static <T> void sort(List<T> list, Comparator<? super T> c) 

Lambda expression 

Collections.sort(students, (o1, o2) -> Student.compareByAge(o1, o2));

Biểu thức lambda của chúng ta chỉ đơn giản là gọi đến method compareByAge() của class Student đã được định nghĩa sẵn

Method references

Collections.sort(students, Student::compareByAge);

Với việc sử dụng method references code của chúng ta lại ngắn thêm được một xíu, đẹp hơn một xíu phải không nào =)))

VD2: Sử dụng stream api để lấy ra danh sách giới tính của các học sinh và in ra màn hình

Lambda expression

students.stream().map(s -> s.getSex()).forEach(e -> System.out.println(e));

Method references

students.stream().map(Student::getSex).forEach(System.out::println);

Note

Các ở chỉ cần hiểu khái niệm và biết khi nào dùng đến method references thôi. Chứ khi bạn code dùng IDE như intelij,v.v thì nó sẽ tự động gợi ý và replace cho bạn.

Source code demo: socurce

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x