java List 排序

文章参考 对List集合中的元素进行排序

对元素是基本数据类型的List排序

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

import org.junit.Test;

public class ListSortTest {

	@Test
	public void testListSortSimple() {

		List nameList = new ArrayList<>();
		nameList.add("serina");
		nameList.add("blair");
		nameList.add("calorin");
		for (String name : nameList) {
			System.out.println("before name = " + name);
		}
		
 		//使用Java中提供的对集合进行操作的工具类Collections,其中的sort方法
		Collections.sort(nameList);
		for (String name : nameList) {
			System.out.println("after name = " + name);
		}
	}

	 

}

对 元素是复杂实体类的List排序

定义实体类Student,实现Comparable接口,实现接口的compareTo()方法

public class Student implements Comparable {

	private String name;
	private Integer age;
	public Student(String name, Integer age) {
		super();
		this.name = name;
		this.age = age;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public int compareTo(Student o) {
		int i = this.getName().compareTo(o.getName());
		if (i == 0) {
			i = this.getAge().compareTo(o.getAge());
		}

		return i;
		// sort desc 降序排列
		// if (i == -1)
		// return 1;
		// if(i == 1)
		// return -1;
		// else {
		// return 0;
		// }
	}

}

测试类

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

import org.junit.Test;

public class ListSortTest {
	@Test
	public void testListSortEntity() {

		List students = new ArrayList<>();
		students.add(new Student("serina", 13));
		students.add(new Student("serina", 10));
		students.add(new Student("blair", 15));
		students.add(new Student("calorin", 16));
		students.add(new Student("calorin", 12));

 		for (Student student : students) {
			System.out.println("before student name = " + student.getName() +" age = "+student.getAge());
		}
		Collections.sort(students); // 排序
		for (Student student : students) {
			System.out.println("after student name = " + student.getName() +" age = "+student.getAge());
		}
	}

}

你可能感兴趣的:(java)