Java: how to sort the elements in the List set (add to favorites), javalist
In java Development, sometimes we need to sort the elements in the List set according to certain rules. For example, if there is a set of persons, we need to sort and output the elements according to the age attribute of Person, this requires the collection tool Collections provided in Java. The sort method is as follows:
1. Person class:
public class Person {private String id;private String name;private int age;public Person(String id, String name, int age) {super();this.id = id;this.name = name;this.age = age;}public String getId() {return id;}public void setId(String id) {this.id = id;}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;}}
2. Sorting class:
Import java. util. arrayList; import java. util. collections; import java. util. comparator; import java. util. list; public class PersonSort {public static void main (String [] args) {List <Person> plist = new ArrayList <Person> (); // create three Person objects, the ages are 32, 20, and 25, respectively, and put them into the List in sequence: Person p1 = new Person ("0001", "zhangsan", 32 ); person p2 = new Person ("0002", "lisi", 20); Person p3 = new Person ("0003", "wangwu", 25); plist. add (p1); plist. add (p2); plist. add (p3); System. out. println ("Result Before sorting:" + plist); Collections. sort (plist, new Comparator <Person> () {/** int compare (Person p1, Person p2) returns an integer of the basic type, * returns a negative number indicating that p1 is less than p2, * If 0 is returned, p1 and p2 are equal. * If positive numbers are returned, p1 is greater than p2 */public int compare (Person p1, Person p2) {// sort by Person age in ascending order if (p1.getAge ()> p2.getAge () {return 1;} if (p1.getAge () = p2.getAge ()) {return 0;} return-1 ;}}); System. out. println ("sorting result:" + plist );}}