首页 > 代码库 > List集合对象中的排序

List集合对象中的排序

 1  List<User> students = new ArrayList<User>();  
 2          
 3          User user1 = new User();
 4          user1.setAge(112);
 5          user1.setUserName("小米");
 6          user1.setMoney(118.55);
 7          students.add(user1);  
 8          
 9          User user2 = new User();
10          user2.setAge(82);
11          user2.setUserName("小王");
12          user2.setMoney(88.55);
13          students.add(user2); 
14          
15          User user3 = new User();
16          user3.setAge(100);
17          user3.setUserName("小李");
18          user3.setMoney(110.65);
19          students.add(user3); 
20          
21          User user4 = new User();
22          user4.setAge(99);
23          user4.setUserName("小赵");
24          user4.setMoney(99.5);
25          students.add(user4); 
26               
27             Collections.sort(students, new Comparator<User>() {  
28                   @Override
29                 public int compare(User o1, User o2) {
30                       //降序
31                       /*if(o1.getMoney()>o2.getMoney()){
32                           return -1;
33                       }
34                       if(o1.getMoney()<o2.getMoney()){
35                           return 1;
36                       }
37                       return 0;*/
38                           
39                       //升序
40                           if(o1.getMoney()>o2.getMoney()){
41                               return 1;
42                           }
43                           if(o1.getMoney()<o2.getMoney()){
44                               return -1;
45                           }
46                           return 0;
47                       
48                      /*int i = o1.getAge() - o2.getAge();  
49                      return i;*/
50                 }  
51             });  
52             for(User stu : students){  
53                 System.out.println("score:" + stu.getUserName() + ":age:" + stu.getAge()+":money:"+stu.getMoney());  
54             }  

简单类型list排序

1 List<Integer> nums = new ArrayList<Integer>();  
2         nums.add(3);  
3         nums.add(5);  
4         nums.add(1);  
5         nums.add(0);  
6         System.out.println(nums);  
7         Collections.sort(nums);  
8         System.out.println(nums);

 

List集合对象中的排序