集合的排序(正序,倒序,从大到小排序)
Posted 我还是那个少年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了集合的排序(正序,倒序,从大到小排序)相关的知识,希望对你有一定的参考价值。
1.简单的集合排序
1 package com.demo.advice; 2 3 import java.util.Collections; 4 import java.util.LinkedList; 5 6 import com.alibaba.druid.sql.visitor.functions.Reverse; 7 8 public class Test { 9 public static void main(String[] args) { 10 11 LinkedList<Integer> list = new LinkedList<Integer>(); 12 list.add(1); 13 list.add(8); 14 list.add(7); 15 list.add(4); 16 list.add(5); 17 //排序前 18 System.out.println(list); 19 //倒序 20 Collections.reverse(list); 21 System.out.println(list); 22 //从大到小排序 23 Collections.sort(list); 24 System.out.println(list); 25 26 } 27 28 }
排序结果图
2.复杂一点的集合排序
1 package com.demo.advice; 2 3 4 import java.util.Collections; 5 import java.util.LinkedList; 6 7 8 9 public class Test { 10 public static void main(String[] args) { 11 LinkedList<Users> list = new LinkedList<Users>(); 12 list.add(new Users(1,"aa",20)); 13 list.add(new Users(4,"bb",30)); 14 list.add(new Users(3,"cc",25)); 15 list.add(new Users(3,"dd",42)); 16 list.add(new Users(8,"ee",35)); 17 Collections.sort(list); 18 for (Users users : list) { 19 System.out.println(users); 20 } 21 } 22 23 }
下面是实体类实现comparable接口
package com.demo.advice; public class Users implements Comparable<Users> { private int id; private String name; private int age; public Users() { super(); // TODO Auto-generated constructor stub } public Users(Integer id, String name, Integer age) { super(); this.id = id; this.name = name; this.age = age; } @Override public String toString() { return "Users [id=" + id + ", name=" + name + ", age=" + age + "]"; } public int getId() { return id; } public void setId(int 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; } @Override public int compareTo(Users o) { int i = this.getId() - o.getId(); if (i==0) { return this.getAge() - o.getAge(); } return i; // TODO Auto-generated method stub } }
比较的结果截图
如果要按姓名排序
以上是关于集合的排序(正序,倒序,从大到小排序)的主要内容,如果未能解决你的问题,请参考以下文章