[个人原创]关于java中对象排序的一些探讨(二)

2.  使用Collections.sort()方法

  Collections类中提供了诸多静态方法,诸如addAll(),max()等等。当自己相对Collection接口下的类处理的时候,可以看看这个工具箱里有没有自己能直接使用的工具。

 1 import java.util.*;
 2 
 3 /**
 4  * Created By IntelliJ IDEA
 5  * User:LeeShuai
 6  * Date:3/6/14
 7  * Time:5:22 PM
 8  */
 9 public class CollectionsTest {
10     public static void main(String[] args) {
11         List<Person> person = new LinkedList<Person>();
12         person.add(new Person("十八子", 60));
13         person.add(new Person("大大的灯泡", 24));
14         person.add(new Person("十八子", 24));
15         person.add(new Person("大连", 22));
16         person.add(new Person("beijing", 54));
17         Collections.sort(person, new Comparator<Person>() {
18             @Override
19             public int compare(Person o1, Person o2) {
20                 int i = new Integer(o2.getAge()).compareTo(new Integer(o1.getAge()));
21                 if (i != 0) {
22                     return i;
23                 }
24                 return o1.getName().compareTo(o2.getName());
25             }
26         });
27         Iterator<Person> it=person.iterator();
28         while(it.hasNext()){
29            Person person1= it.next();
30           System.out.println(String.format("名字:%s,年龄:%d",person1.getName(),person1.getAge()));
31         }
32     }
33 
34 }

运行结果:

1 名字:十八子,年龄:60
2 名字:beijing,年龄:54
3 名字:十八子,年龄:24
4 名字:大大的灯泡,年龄:24
5 名字:大连,年龄:22
原文地址:https://www.cnblogs.com/shibazijiang/p/3584961.html