java如何对List集合中的元素进行排序(请收藏)

转载自:https://www.cnblogs.com/wangyayun/p/7852075.html

在java开发中有时候我们需要对List集合中的元素按照一定的规则进行排序,比如说有个Person的集合,我们要根据Person的age属性进行排序输出,这就需要用到Java中提供的对集合进行操作的工具类Collections,其中的sort方法,大家看虾米哥的例子如下:

1.Person类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package  www.itxm.net;
 
public  class  Person {
     private  String id;
     private  String name;
     private  int  age;
     
     public  Person(String id, String name,  int  age) {
         super ();
         this .id = id;
         this .name = name;
         this .age = age;
     }
     public  String getId() {
         return  id;
     }
     public  void  setId(String 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;
     }
}

 2.排序类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package  www.itxm.net;
 
import  java.util.ArrayList;
import  java.util.Collections;
import  java.util.Comparator;
import  java.util.List;
 
public  class  PersonSort {
     public  static  void  main(String[] args) {
         List<Person> plist =  new  ArrayList<Person>(); 
         //创建3个Person对象,年龄分别是32、20、25,并将他们依次放入List中 
         Person p1 =  new  Person( "0001" , "zhangsan" , 32 );
         Person p2 =  new  Person( "0002" , "lisi" , 20 );
         Person p3 =  new  Person( "0003" , "wangwu" , 25 );
         plist.add(p1);
         plist.add(p2);
         plist.add(p3);
         System.out.println( "排序前的结果:" +plist);
         Collections.sort(plist,  new  Comparator<Person>(){
             /*
              * int compare(Person p1, Person p2) 返回一个基本类型的整型,
              * 返回负数表示:p1 小于p2,
              * 返回0 表示:p1和p2相等,
              * 返回正数表示:p1大于p2
              */
             public  int  compare(Person p1, Person p2) {
                 //按照Person的年龄进行升序排列
                 if (p1.getAge() > p2.getAge()){
                     return  1 ;
                 }
                 if (p1.getAge() == p2.getAge()){
                     return  0 ;
                 }
                 return  - 1 ;
             }
         });
         System.out.println( "排序后的结果:" +plist); 
     }
}

 3.总结:

本排序最核心的Collections工具类的使用,牢牢掌握,遇到排序的时候不会手忙脚乱。


猜你喜欢

转载自blog.csdn.net/meng19910117/article/details/80939412