欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

对JsonArray根据JsonObject中的某一字段排序

程序员文章站 2022-07-09 13:46:57
方式一:Collections.sort(list, new Comparator() {})List list = JSONArray.parseArray(resultArrays.toJSONString(), JSONObject.class);Collections.sort(list, new Comparator() { //排序字段 private final String FIELD_NAME =...

方式一: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";
    //重写compare方法
    @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);

​​// 对List<JsonObject>里的某字段进行快速排序
private static void quickSort(JSONArray arr, int low, int high) {
    if (low < high) {
        // 找寻基准数据的正确索引
        int index = getIndex(arr, low, high);
        // 进行迭代对index之前和之后的数组进行相同的操作使整个数组变成有序
        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) {
        // 当队尾的元素大于等于基准数据时,向前挪动high指针
        while (low < high && arr.getJSONObject(high).getIntValue("num") >= tmpNum) {
            high--;
        }
        // 如果队尾元素小于tmp了,需要将其赋值给low
        arr.add(low, arr.getJSONObject(high));
        // 当队首元素小于等于tmp时,向前挪动low指针
        while (low < high && arr.getJSONObject(low).getIntValue("num") <= tmpNum) {
            low++;
        }
        // 当队首元素大于tmp时,需要将其赋值给high
        arr.add(high, arr.getJSONObject(low));
    }
    // 跳出循环时low和high相等,此时的low或high就是tmp的正确索引位置
    // 由原理部分可以很清楚的知道low位置的值并不是tmp,所以需要将tmp赋值给arr[low]
    arr.add(low, tmpObject);
    return low; // 返回tmp的正确位置
}

本文地址:https://blog.csdn.net/awen6666/article/details/107597685