欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java集合Collections.sort()的方法应用

程序员文章站 2022-05-12 17:49:02
...

简单介绍集合工具类sort()的方法应用,简单类型排序和根据对象字段来排序.代码如下:

public class SomeTest {
	public static void main(String[] args) {
		SomeTest st = new SomeTest();
		List<String> list = new ArrayList<>();
		list.add("bu");
		list.add("cu");
		list.add("ca");
		list.add("a");
		Collections.sort(list);//简单排序
		System.out.println(list);
		//对象排序
		List<employee> strList = new ArrayList<>();
		employee e1 = st.new employee("bily", 10, 18000);
		employee e2 = st.new employee("fulosa", 10, 16000);
		employee e3 = st.new employee("aiwen", 10, 17000);
		employee e4 = st.new employee("cicy", 10, 13000);
		strList.add(e1);
		strList.add(e2);
		strList.add(e3);
		strList.add(e4);
		/**有几种自定义API,根据类型来选择*/
		strList.sort(Comparator.comparingDouble(employee::getSalary));//排序,根据工资
		System.out.println(strList.toString());
		strList.sort(Comparator.comparingDouble(employee::getSalary).reversed());//自定义排序逆序
		System.out.println(strList.toString());
		strList.sort(Comparator.comparing(employee::getName));//根据名字排序,调用String类型的比较方法
		System.out.println(strList.toString());
	}
	class employee{
		private String name;
		private int age;
		private double salary;
		public employee(String name,int age, double salary){
			this.name=name;
			this.age=age;
			this.salary=salary;
		}
		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 double getSalary() {
			return salary;
		}
		public void setSalary(double salary) {
			this.salary = salary;
		}
		@Override
		public String toString() {
			return "employee [name=" + name + ", age=" + age + ", salary=" + salary + "]";
		}		
	}
}

结果输出:

[a, bu, ca, cu]
[employee [name=cicy, age=10, salary=13000.0], employee [name=fulosa, age=10, salary=16000.0], employee [name=aiwen, age=10, salary=17000.0], employee [name=bily, age=10, salary=18000.0]]
[employee [name=bily, age=10, salary=18000.0], employee [name=aiwen, age=10, salary=17000.0], employee [name=fulosa, age=10, salary=16000.0], employee [name=cicy, age=10, salary=13000.0]]
[employee [name=aiwen, age=10, salary=17000.0], employee [name=bily, age=10, salary=18000.0], employee [name=cicy, age=10, salary=13000.0], employee [name=fulosa, age=10, salary=16000.0]]

相关标签: sort 集合排序