JSONArray根据某个key进行排序,注意key的类型。
1、只支持JDK1.8以上版本
private static JSONArray sortProxyAndCdn(JSONArray bindArrayResult) {
System.out.println("排序前:"+bindArrayResult);
bindArrayResult.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("cdn").length()).reversed());
System.out.println("排序后:" + bindArrayResult);
return bindArrayResult;
}
2、通用版本
private static JSONArray sortProxyAndCdn(JSONArray bindArrayResult) {
List<JSONObject> list = JSONArray.parseArray(bindArrayResult.toJSONString(), JSONObject.class);
System.out.println("排序前:"+bindArrayResult);
Collections.sort(list, new Comparator<JSONObject>() {
@Override
public int compare(JSONObject o1, JSONObject o2) {
int a = o1.getString("cdn").length();
int b = o2.getString("cdn").length();
if (a > b) {
return -1;
} else if(a == b) {
return 0;
} else
return 1;
}
});
JSONArray jsonArray = JSONArray.parseArray(list.toString());
System.out.println("排序后:"+jsonArray);
return jsonArray;
}