List(JSONArray)排序

		List<JSONObject> list=JSONArray.parseArray("[{\"name\":\"北京\",\"value\":232},{\"name\":\"天津\",\"value\":140},{\"name\":\"河北\",\"value\":624},{\"name\":\"山西\",\"value\":421},{\"name\":\"内蒙\",\"value\":145},{\"name\":\"辽宁\",\"value\":59},{\"name\":\"吉林\",\"value\":71},{\"name\":\"黑龙江\",\"value\":306},{\"name\":\"上海\",\"value\":377},{\"name\":\"江苏\",\"value\":327},{\"name\":\"浙江\",\"value\":1073},{\"name\":\"安徽\",\"value\":209},{\"name\":\"福建\",\"value\":98},{\"name\":\"江西\",\"value\":704},{\"name\":\"山东\",\"value\":1252},{\"name\":\"河南\",\"value\":2101},{\"name\":\"湖北\",\"value\":383},{\"name\":\"湖南\",\"value\":203},{\"name\":\"广东\",\"value\":360},{\"name\":\"广西\",\"value\":98},{\"name\":\"海南\",\"value\":727},{\"name\":\"重庆\",\"value\":341},{\"name\":\"四川\",\"value\":173},{\"name\":\"贵州\",\"value\":213},{\"name\":\"云南\",\"value\":163},{\"name\":\"西藏\",\"value\":12},{\"name\":\"陕西\",\"value\":765},{\"name\":\"甘肃\",\"value\":144},{\"name\":\"青海\",\"value\":74},{\"name\":\"宁夏\",\"value\":292},{\"name\":\"新疆\",\"value\":189},{\"name\":\"台湾\",\"value\":0},{\"name\":\"香港\",\"value\":0},{\"name\":\"澳门\",\"value\":0}]",JSONObject.class);
        list.sort(new Comparator<>() {
            // 根据value这个字段排序
            private static final String KEY_NAME = "value";
            @Override
            public int compare(JSONObject a, JSONObject b) {
                Integer valA = a.getInteger(KEY_NAME);
                Integer valB = b.getInteger(KEY_NAME);
                // valA 不能是基本数据类型
                return -valA.compareTo(valB);
//                return -valB.compareTo(valA);//正序
            }
        });
        for (JSONObject object : list) {
            System.out.println(object.getString("value"));
        }
        System.out.println(JSON.toJSONString(list));

你可能感兴趣的:(java,排序,java,排序)