侧边栏壁纸
博主头像
JavaLYG 博主等级

行动起来,活在当下

  • 累计撰写 32 篇文章
  • 累计创建 8 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

JSONArray根据某个字段进行排序

liuyg
2023-01-04 / 0 评论 / 0 点赞 / 41 阅读 / 0 字 / 正在检测是否收录...

业务过程中遇到需要对订单列表jsonarray进行排序,可以用此方法。

getDate("createTime") createTime修改为你需要排序字段的key
public static void main(String[] args) {
        JSONArray orders = new JSONArray();
        JSONObject order1 = new JSONObject();
        order1.put("name","短袖");
        order1.put("type","衣服");
        order1.put("createTime","2022-08-09");
        JSONObject order2 = new JSONObject();
        order2.put("name","帽子");
        order2.put("type","衣服");
        order2.put("createTime","2022-07-07");
        JSONObject order3 = new JSONObject();
        order3.put("name","袜子");
        order3.put("type","衣服");
        order3.put("createTime","2022-08-02");
        orders.add(order1);
        orders.add(order2);
        orders.add(order3);
        System.out.println("排序前:");
        for (int i = 0; i < orders.size(); i++) {
            JSONObject jsonObject = (JSONObject) orders.get(i);
            System.out.println(jsonObject);
        }
        orders.sort(Comparator.comparing(obj->((JSONObject)obj).getDate("createTime"),Comparator.nullsFirst(Comparator.naturalOrder())));
        System.out.println("正序排序后:");
        for (int i = 0; i < orders.size(); i++) {
            JSONObject jsonObject = (JSONObject) orders.get(i);
            System.out.println(jsonObject);
        }
        orders.sort(Comparator.comparing(obj->((JSONObject)obj).getDate("createTime"),Comparator.nullsFirst(Comparator.naturalOrder())).reversed());
        System.out.println("倒叙排序后:");
        for (int i = 0; i < orders.size(); i++) {
            JSONObject jsonObject = (JSONObject) orders.get(i);
            System.out.println(jsonObject);
        }
    }

结果输出:20220830185919850.jpg

0

评论区