JSONArray内元素排序

现在有一组JSONArray数据,我想以其中一种元素来排序(我这里这个元素是int),这在实际工作中还是经常遇到的,主要是通过重写Comparator。
数据

[{"repayTerm":"3","test":"2018-12-09"},
{"repayTerm":"1","test":"2018-12-19"},
{"repayTerm":"2","test":"2018-12-13"}]  

第一版

jta.sort(new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return ((JSONObject)o1).getIntValue("repayTerm")-((JSONObject)o2).getIntValue("repayTerm");
            }
        });

befor:
[{"repayTerm":"3","test":"2018-12-09"},
{"repayTerm":"1","test":"2018-12-19"},
{"repayTerm":"2","test":"2018-12-13"}]
after:
[{"repayTerm":"1","test":"2018-12-19"},
{"repayTerm":"2","test":"2018-12-13"},
{"repayTerm":"3","test":"2018-12-09"}]

第二版

        jta.sort(((a,b)->((JSONObject)a).getIntValue("repayTerm")-((JSONObject)b).getIntValue("repayTerm")));

befor:
[{"repayTerm":"3","test":"2018-12-09"},
{"repayTerm":"1","test":"2018-12-19"},
{"repayTerm":"2","test":"2018-12-13"}]
after:
[{"repayTerm":"1","test":"2018-12-19"},
{"repayTerm":"2","test":"2018-12-13"},
{"repayTerm":"3","test":"2018-12-09"}]

第三版

        jta.sort(Comparator.comparing(ele -> ((JSONObject) ele).getIntValue("repayTerm")));

befor:
[{"repayTerm":"3","test":"2018-12-09"},
{"repayTerm":"1","test":"2018-12-19"},
{"repayTerm":"2","test":"2018-12-13"}]
after:
[{"repayTerm":"1","test":"2018-12-19"},
{"repayTerm":"2","test":"2018-12-13"},
{"repayTerm":"3","test":"2018-12-09"}]

三版实际上都是做的同样的事情,寻求简洁优雅用第三版,求真务实追本溯源用第一版,第二版属于中庸,简洁且直观。

你可能感兴趣的:(经验)