首页 > 代码库 > java范型集合中的成员排序

java范型集合中的成员排序

范型集合中的类是JsonObject,不是自定义类,如果是自定义类就直接取要比较的字段值。

 1   ArrayList<JSONObject> TList = new ArrayList<JSONObject>();
 2  
 3                for(int i=0;i<10000;i++)
 4                 {
 5                     JSONObject object=new JSONObject();
 6                     Random rand = new Random();
 7                     int randNum = rand.nextInt(2000000)+5;
 8                     String Value=http://www.mamicode.com/String.valueOf(randNum);
 9                     try {
10                         object.put("value", Value);
11                         object.put("name", "liaohang");
12                     } catch (JSONException e) {
13                         // TODO Auto-generated catch block
14                         e.printStackTrace();
15                     }
16                     TList.add(object) ;
17                     
18                      
19                     
20                 }
21               
22               
23               
24                  Collections.sort( TList, new Comparator<JSONObject>() {
25                      //You can change "Name" with "ID" if you want to sort by ID
26                      private static final String KEY_NAME = "value";
27 
28                      @Override
29                      public int compare(JSONObject a, JSONObject b) {
30                          int valA =0;
31                          int valB =0;
32 
33                          try {
34                              valA = Integer.parseInt((String) a.get(KEY_NAME));
35                              valB = Integer.parseInt((String) b.get(KEY_NAME));
36                          } 
37                          catch (JSONException e) {
38                              //do something
39                          }
40                         return valA > valB ? 1 : -1;
41                          
42                        //  return valA.compareTo(valB);
43                          //if you want to change the sort order, simply use the following:
44                          //return -valA.compareTo(valB);
45                      }
46                  });
47                
48               
49                //打印排序后的结果
50               String  printValue=http://www.mamicode.com/null;
51                 for(int i=0;i<TList.size();i++)
52                 {
53                   JSONObject obect=TList.get(i)  ;
54                   try {
55                        printValue=http://www.mamicode.com/obect.getString("value");
56                 } catch (JSONException e) {
57                     // TODO Auto-generated catch block
58                     e.printStackTrace();
59                 }
60                        
61                   System.out.println(printValue);
62                   
63                 }

 

java范型集合中的成员排序