標籤:compare sort hang cat i++ ide eth nal color
範型集合中的類是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=String.valueOf(randNum); 9 try {10 object.put("value", Value);11 object.put("name", "liaohang");12 } catch (JSONException e) {13 // TODO Auto-generated catch block14 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 ID26 private static final String KEY_NAME = "value";27 28 @Override29 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 something39 }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=null;51 for(int i=0;i<TList.size();i++)52 {53 JSONObject obect=TList.get(i) ;54 try {55 printValue=obect.getString("value");56 } catch (JSONException e) {57 // TODO Auto-generated catch block58 e.printStackTrace();59 }60 61 System.out.println(printValue);62 63 }
java範型集合中的成員排序