list集合按元素的某一屬性排序

專注的阿熊發表於2019-08-29
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
40
41
42
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
  * ClassName: Sort
  * @Description: list集合按元素的某一屬性排序
  * @author ljw
  * @date 2018年5月24日
  */
public class Sort {
     
     public static void main(String[] args) {
         
         List<Map<String, Integer>> list = new ArrayList<>();
         
         for ( int i = 0 ; i < 10 ; i++) {
             Map<String, Integer> map = new HashMap<>();
             Integer random = ( int )(Math.random() * 100 );
             map.put( "random" , random);
             list.add(map);
         }
         
         //排序前
         System.out.println( "排序前:" + list);
         
         Collections.sort(list, new Comparator<Map<String, Integer>>() {
             public int compare(Map<String, Integer> m1, Map<String, Integer> m2) {
                 //降序
                 //return m2.get("random").compareTo(m1.get("random"));
                 //升序
                 return m1.get( "random" ).compareTo(m2.get( "random" ));               
             }
         });
         
         //排序後
         System.out.println( "排序後:" + list);
     }
}

 
排序前:[{random=79}, {random=44}, {random=38}, {random=65}, {random=43}, {random=83}, {random=90}, {random=87}, {random=83}, {random=13}]
 
排序後:[{random=13}, {random=38}, {random=43}, {random=44}, {random=65}, {random=79}, {random=83}, {random=83}, {random=87}, {random=90}]


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2655456/,如需轉載,請註明出處,否則將追究法律責任。

相關文章