The objects in the List collection are sorted according to the property

 

The data stored in the collection class List is stored in the order in which it was placed by default. For example, if A, B, and C are placed in sequence, when they are obtained, they are also in the order of A, B, and C. In actual scenarios, sometimes we need to How to sort the elements in the List with custom rules? See the following small example:

package test.tool.gui.dbtool.util;

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

public class Test {

	public static void main(String[] args) {
		
		List<Student> list = new ArrayList<Student>();
		
		//Create 3 student objects, the ages are 20, 19, 21, and put them into the List in turn
		Student s1 = new Student();
		s1.setAge (20);
		Student s2 = new Student();
		s2.setAge(19);
		Student s3 = new Student();
		s3.setAge(21);
		list.add(s1);
		list.add(s2);
		list.add(s3);
		
		System.out.println("Before sorting: "+list);
		
		Collections.sort(list, new Comparator<Student>(){

			/*
			 * int compare(Student o1, Student o2) returns a primitive integer,
			 * Return a negative number to indicate: o1 is less than o2,
			 * Return 0 means: o1 and o2 are equal,
			 * Returns a positive number indicating: o1 is greater than o2.
			 */
			public int compare(Student o1, Student o2) {
			
				// Sort the students in ascending order by age
				if(o1.getAge() > o2.getAge()){
					return 1;
				}
				if(o1.getAge() == o2.getAge()){
					return 0;
				}
				return -1;
			}
		});
		System.out.println("After sorting: "+list);
	}
}
class Student{
	
	private int age;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return getAge()+"";
	}
}

 

Results of the:

  1. Before sorting: [20, 19, 21]  
  2. After sorting: [19, 20, 21]  

 

Of course, there can be multiple attributes of the object, such as ascending order by age, descending order by grade, etc.

 

http://blog.csdn.net/lifuxiangcaohui/article/details/41543347

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327026876&siteId=291194637