实现 Collections 中自定义排序的两种方式

  • 集合中元素实现 Comparable 接口
package 集合;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;

public class Test {
	
	public static void main(String[] args) {
		LinkedList<Stu> s = new LinkedList<>();
		Stu s1 = new Stu("张三", 19);
		Stu s2 = new Stu("李四", 20);
		Stu s3 = new Stu("王五", 17);
		s.add(s1);
		s.add(s2);
		s.add(s3);
		for (Stu stu : s) {
			System.out.println(stu);
		}
		Collections.sort(s);
		System.out.println("---排序后-------");
		for (Stu stu : s) {
			System.out.println(stu);
		}
		
	}
}
class Stu implements Comparable<Stu>{
	private String name;
	private int age;
	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;
	}
	public Stu(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Stu [name=" + name + ", age=" + age + "]";
	}
	@Override
	public int compareTo(Stu o) {
		return this.getAge() - o.getAge();
	}
}

Stu [name=张三, age=19]
Stu [name=李四, age=20]
Stu [name=王五, age=17]
---排序后-------
Stu [name=王五, age=17]
Stu [name=张三, age=19]
Stu [name=李四, age=20]
  • 使用比较器 Comparator
package 集合;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;

public class Test {
	
	public static void main(String[] args) {
		LinkedList<Stu> s = new LinkedList<>();
		Stu s1 = new Stu("张三", 19);
		Stu s2 = new Stu("李四", 20);
		Stu s3 = new Stu("王五", 17);
		s.add(s1);
		s.add(s2);
		s.add(s3);
		for (Stu stu : s) {
			System.out.println(stu);
		}
		Collections.sort(s, new Comparator<Stu>() {
			@Override
			public int compare(Stu o1, Stu o2) {
				// TODO Auto-generated method stub
				return o1.getAge() - o2.getAge();
			}
		});
		System.out.println("---排序后-------");
		for (Stu stu : s) {
			System.out.println(stu);
		}
		
	}
}

class Stu{
	private String name;
	private int age;
	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;
	}
	public Stu(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
		return "Stu [name=" + name + ", age=" + age + "]";
	}
}

Stu [name=张三, age=19]
Stu [name=李四, age=20]
Stu [name=王五, age=17]
---排序后-------
Stu [name=王五, age=17]
Stu [name=张三, age=19]
Stu [name=李四, age=20]
上一篇:Request应用


下一篇:财报背后的阿里数字经济体:战略定力与运营效力