美文网首页
JSONArray进行排序

JSONArray进行排序

作者: wanggs | 来源:发表于2019-07-09 09:49 被阅读0次

    前言

    根据业务需要,需要把前端传的JSONArray,按照week升序排序

    环境

    • JDK 1.8.0 +
    • Maven 3.0 +
    • Redis 2.4.2
    • SpringBoot 2.0.3

    开发工具

    • IntelliJ IDEA

    正文

    前端传入json数据
    String str = "[{\"endTime\":\"24:00\",\"startTime\":\"00:00\",\"week\":4},{\"endTime\":\"24:00\",\"startTime\":\"00:00\",\"week\":1},{\"endTime\":\"24:00\",\"startTime\":\"00:00\",\"week\":0},{\"endTime\":\"24:00\",\"startTime\":\"00:00\",\"week\":3},{\"endTime\":\"24:00\",\"startTime\":\"00:00\",\"week\":2},{\"endTime\":\"24:00\",\"startTime\":\"00:00\",\"week\":5},{\"endTime\":\"24:00\",\"startTime\":\"00:00\",\"week\":6}]";
    
            System.out.println("-------排序前---------");
            JSONArray array = JSONArray.fromObject(str);
            array.forEach(e->{
                System.out.println(e);
            });
            
            array.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInt("week")));
            
            System.out.println("-------排序后---------");
            array.forEach(e->{
                System.out.println(e);
            });
    

    输出

    -------排序前---------
    {"endTime":"24:00","startTime":"00:00","week":4}
    {"endTime":"24:00","startTime":"00:00","week":1}
    {"endTime":"24:00","startTime":"00:00","week":0}
    {"endTime":"24:00","startTime":"00:00","week":3}
    {"endTime":"24:00","startTime":"00:00","week":2}
    {"endTime":"24:00","startTime":"00:00","week":5}
    {"endTime":"24:00","startTime":"00:00","week":6}
    -------排序后---------
    {"endTime":"24:00","startTime":"00:00","week":0}
    {"endTime":"24:00","startTime":"00:00","week":1}
    {"endTime":"24:00","startTime":"00:00","week":2}
    {"endTime":"24:00","startTime":"00:00","week":3}
    {"endTime":"24:00","startTime":"00:00","week":4}
    {"endTime":"24:00","startTime":"00:00","week":5}
    {"endTime":"24:00","startTime":"00:00","week":6}
    
    降序排序
    
    staffArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getBigDecimal("orderAmt")).reversed());
    
    我的是根据数字大小来比较,还可以根据你自定义属性来比较,很方便的
    
    

    根据对象排序

                // 根据距离排序
    /*            recordList.sort(new Comparator<Record>() {
                    @Override
                    public int compare(Record o1, Record o2) {
                        return o1.getInt("distance") - o2.getInt("distance");
                    }
                });*/
    

    相关文章

      网友评论

          本文标题:JSONArray进行排序

          本文链接:https://www.haomeiwen.com/subject/msytkctx.html