本人开发的开发者技术变现资源聚集地,大家支持下,下面是网址
https://www.baiydu.com
范型集合中的类是JsonObject,不是自定义类,如果是自定义类就直接取要比较的字段值。
ArrayList<JSONObject> TList = new ArrayList<JSONObject>(); for(int i=0;i<10000;i++)
{
JSONObject object=new JSONObject();
Random rand = new Random();
int randNum = rand.nextInt(2000000)+5;
String Value=String.valueOf(randNum);
try {
object.put("value", Value);
object.put("name", "liaohang");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TList.add(object) ; } Collections.sort( TList, new Comparator<JSONObject>() {
//You can change "Name" with "ID" if you want to sort by ID
private static final String KEY_NAME = "value"; @Override
public int compare(JSONObject a, JSONObject b) {
int valA =0;
int valB =0; try {
valA = Integer.parseInt((String) a.get(KEY_NAME));
valB = Integer.parseInt((String) b.get(KEY_NAME));
}
catch (JSONException e) {
//do something
}
return valA > valB ? 1 : -1; // return valA.compareTo(valB);
//if you want to change the sort order, simply use the following:
//return -valA.compareTo(valB);
}
}); //打印排序后的结果
String printValue=null;
for(int i=0;i<TList.size();i++)
{
JSONObject obect=TList.get(i) ;
try {
printValue=obect.getString("value");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} System.out.println(printValue); }