[Java Object-Oriented] Use the Lambda expression comparator Comparator to sort List objects

background introduction

Lambda expression is a new feature provided in JAVA8, which is an anonymous function method. Lambda expressions can be understood as a piece of code that can be passed, and more concise and flexible code can be written.

Lambda expressions are the implementation of abstract methods in functional interfaces, and are shorthand for anonymous inner classes. Only the parameter list and method body of the method are retained, and other components can be omitted. Therefore, the format of a Lambda expression is very concise, consisting of only three parts:

  • parameter list

  • arrow

  • method body

That is (parameter list) -> {method body}

Experimental content

Use the Lambda expression comparator Comparator to sort the List objects by Name, Age (reverse order), and Grade respectively. The content of the List object is as follows:

ID

Name

Age

Grade

1

ZhangSan

28

98

2

LiSi

21

100

3

KangKang

27

89

4

LiMing

19

92

5

Wang Gang

22

66

6

Zhao Xin

24

85

7

LiuWei

20

78

8

Bai Zhan Tang

16

99

(1) Experiment ideas

① Define the class Info, regard the contents to be compared as member variables in the Info class, and sort by comparing the values ​​of the member variables. Set four member variables: ID of type int, name of type String, age of type int and grade of type int, and set them as private.

②Set the get method of each member variable, and overload the toString method to output personal information.

③ Define the class Test, and define the List whose element type is the Info class in the main method. Enter the information of 8 people into the List by creating an Info instance.

④Use the sort method in the Comparator interface to sort the elements in the List to simplify the comparison and meet the meaning of the question. The function in sort uses lambda expression. For the name of String type, use the compareTo method for comparison; for the age and grade of Integer type, use the compare method of the Integer class for comparison.

⑤ Use the foreach statement to output the elements in the List.

(2) Experiment source code

Info class:

public class Info{
    private int ID;
    private String name;
    private int age;
    private int grade;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public int getGrade() {
        return grade;
    }

    Info(int ID,String name,int age,int grade){
        this.ID=ID;
        this.name=name;
        this.age=age;
        this.grade=grade;
    }

    public String toString() {
        return "ID:"+ID+" "+"Name:"+name+" "+"Age:"+age+" "+"Grade:"+grade+" ";
    }
}

Test class:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        List<Info> myList = new ArrayList<>();
        myList.add(new Info(1, "ZhangSan", 28, 98));
        myList.add(new Info(2, "LiSi", 21, 100));
        myList.add(new Info(3, "KangKang", 27, 89));
        myList.add(new Info(4, "LiMing", 19, 92));
        myList.add(new Info(5, "WangGang", 22, 66));
        myList.add(new Info(6, "ZhaoXin", 24, 85));
        myList.add(new Info(7, "LiuWei", 20, 78));
        myList.add(new Info(8, "BaiZhanTang", 16, 99));

        myList.sort((Info i1, Info i2) -> (i1.getName()).compareTo(i2.getName()));
        System.out.println("按Name排序:");
        for (Info elem : myList) {
            System.out.println(elem.toString());
        }

        myList.sort((Info i1, Info i2) -> (Integer.compare(i1.getAge(), i2.getAge())));
        Collections.reverse(myList);
        System.out.println("\n按Age倒序排序:");
        for (Info elem : myList) {
            System.out.println(elem.toString());
        }

        myList.sort((Info i1, Info i2) -> (Integer.compare(i1.getGrade(), i2.getGrade())));
        System.out.println("\n按Grade排序:");
        for (Info elem : myList) {
            System.out.println(elem.toString());
        }

    }
}

(3) Run the screenshot

(4)实验心得

此题中共有三个难点。

第一个难点在于List的学习与使用。在此之前,我们很少接触List,如何使用List成为了一个很大的困难。

第二个难点在于lambda表达式的使用,如何使用lambda表达式编写简单易懂的函数表达式成为了一个困难。通过简单的“->”,我实现了匿名函数的书写,更加方便地实现了排序函数。

第三个难点在于使用Comparator接口下的sort函数排序时的函数编写。其一在于,sort函数的使用需要一定基础;其二在于比较函数的编写。String类型的比较可以通过compareTo直接返回int值;由于int类型无法使用comapreTo语句,三元运算符比较又显冗长繁琐,如何对int(Integer)类型的成员进行比较成为了一个困难。通过使用Integer类型自带的compare方法,可以成功解决这一问题。

Guess you like

Origin blog.csdn.net/ayaishere_/article/details/128711861