Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How does java sort the objects in ArrayList according to an attribute of the objects?
How does java sort the objects in ArrayList according to an attribute of the objects?
There are several ways to achieve this: let students implement the Comparable interface, or instantiate a comparator.

Now let's take the example of a comparator as an example: ComparableTest.java.

Import java.util.ArrayList;

Import java.util.collections;

Import java.util.comparator;

Common class comparison test {

Public static void main(String[] args) {

Comparator & lt student & gt comparator = new comparator & lt student & gt(){

Public int compare (student s 1, student s2) {

//Age is preferred

if(s 1.age! =s2.age){

Returns s1.age-s2.age;

}

Otherwise {

//Sort by name of the same age.

If (! s 1 . name . equals(S2 . name)){

Return s1.name.compareto (s2.name);

}

Otherwise {

//If the names are the same, sort by student number.

Returns s1.id-s2.id;

}

}

}

};

Stu 1 = freshman (1, "Zhang San", "Male", 28, "CS");

Stu2 = freshman (2, "Li Si", "female", 19, "CS");

Stu3 = new student (3, "King of Wu", "Male", 22, "CS");

Stu4 = freshman (4, "Liu Zhao", "female", 17, "CS");

Stu5 = freshman (5, "first name", "male", 22, "CS");

ArrayList & lt student & gtList = new ArrayList & lt student & gt ();

list . add(stu 1);

list . add(stu 2);

list . add(stu 3);

list . add(stu 4);

list . add(stu 5);

//This will be sorted automatically according to the rules.

Collections.sort(List,comparator);

To display (a list);

}

Static void display (ArrayList & lt student & gt lst) (

For (student: first place)

system . out . println(s);

}

}

Class students {

int age

int id

String gender;

String name;

String cs;

Student (integer id, string name, string gender, integer age, string cs){

This.age = age;

this.name = name

This.gender = gender;

this.id = id

this.cs = cs

}

Common string toString(){

Return id+" "+ name+""+gender+""+age+""+CS;

}

}