方式一:Collections.sort(list, new Comparator() {})
List<JSONObject> list = JSONArray.parseArray(resultArrays.toJSONString(), JSONObject.class);
Collections.sort(list, new Comparator<JSONObject>() {
private final String FIELD_NAME = "num";
@Override
public int compare(JSONObject obj1, JSONObject obj2) {
int val1 = obj1.getIntValue(FIELD_NAME);
int val2 = obj2.getIntValue(FIELD_NAME);
return val2 - val1;
}
});
return JSONArray.parseArray(list.toString());
方式二:使用JsonArray.sort()
resultArrays.sort(Comparator.comparing(obj -> ((JSONObject) obj).getIntValue("num")).reversed());
- resultArrays.sort(Comparator.comparing(obj -> ((JSONObject) obj).getIntValue(“num”))); 升序
- resultArrays.sort(Comparator.comparing(obj -> ((JSONObject) obj).getIntValue(“num”)).reversed()); 降序
方式三:快速排序(不推荐使用,当数组元素大于25后,效率低)
quickSort(resultArrays, 0, 25);
private static void quickSort(JSONArray arr, int low, int high) {
if (low < high) {
int index = getIndex(arr, low, high);
quickSort(arr, 0, index - 1);
quickSort(arr, index + 1, high);
}
}
private static int getIndex(JSONArray arr, int low, int high) {
JSONObject tmpObject = arr.getJSONObject(low);
int tmpNum = tmpObject.getIntValue("num");
while (low < high) {
while (low < high && arr.getJSONObject(high).getIntValue("num") >= tmpNum) {
high--;
}
arr.add(low, arr.getJSONObject(high));
while (low < high && arr.getJSONObject(low).getIntValue("num") <= tmpNum) {
low++;
}
arr.add(high, arr.getJSONObject(low));
}
arr.add(low, tmpObject);
return low;
}