用java的Comparator给JsonArray、TreeMap、HashMap排序

  • JsonArray排序:
public List getSortJsonList(JSONArray jsonArray){
        List jsonObjectList=new ArrayList();
        for(int i=0;i String.valueOf(a.get("day_id")).compareTo(String.valueOf(b.get("day_id"))));//升序
        //老版本的写法
        Collections.sort(jsonObjectList, new Comparator(){
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                String s1 = String.valueOf(o1.get("day_id"));
                String s2 = String.valueOf(o2.get("day_id"));
                return  s1.compareTo(s2);  //升序
            }
        });
        return jsonObjectList;
    }

:http://blog.csdn.net/linshutao/article/details/7693625
TreeMap不是按照hashCode来存放,它是按照实现的Comparable接口的compareTo这个方法来存储的

  • TreeMap(通过key)排序:
 public TreeMap getSortTreeMapByKey(JSONArray jsonArray){
        //下面一段可用lambda表达式代替
        //TreeMap map = new TreeMap((o1,o2)->o2.compareTo(o1));
        TreeMap map = new TreeMap(new Comparator(){
            public int compare(String o1,String o2){
                return  o2.compareTo(o1); //升序
            }
        });
        map.put("2017-09-30", "6");
        map.put("2017-09-29", "2");
        map.put("2017-09-28", "7");
        map.put("2017-09-27", "1");
        for(Map.Entry entry:map.entrySet()){
            System.out.println("key:"+entry.getKey()+",:value:"+entry.getValue());
        }
         return map;
    }
  • TreeMap(通过value)排序:
 public TreeMap getSortTreeMapByValue(JSONArray jsonArray){
        TreeMap map = new TreeMap<>();
        map.put("zdef","rfgh");
        map.put("asrg","zfg");
        map.put("rgd","dfgh");
        map.put("cbf","gddf");
        //将Map转为List
        List> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator>() {
            public int compare(Map.Entry o1, Map.Entry o2) {
                return  o2.getValue().compareTo(o1.getValue());//降序
            }
        });
        //运用lambda表达式
        //Collections.sort(list,((o1, o2) -> o2.getValue().compareTo(o1.getValue())));
        for(Map.Entry entry:list){
            System.out.println("key:"+entry.getKey()+",:value:"+entry.getValue());
        }
        return map;
    }

:http://www.cnblogs.com/pear-lemon/archive/2015/05/28/4536152.html
HashMap的存储位置是按照key这个对象的hashCode来存放的

  • HashMap(通过key)排序( 把数据放在list里边才可以使用):
 public static Map getSortHashMapByKey(){
        Map map = new HashMap();
        map.put("2017-09-30", "6");
        map.put("2017-09-29", "2");
        map.put("2017-09-28", "7");
        map.put("2017-09-27", "1");

        List> list = new ArrayList>();
        list.addAll(map.entrySet());

        KeyComparator kc = new KeyComparator();//升序
        Collections.sort(list, kc);
        for (Iterator> it = list.iterator(); it
                .hasNext();) {
            System.out.println(it.next());
        }
         return map;
    }

private static class KeyComparator implements
            Comparator> {
        public int compare(Map.Entry m,
                           Map.Entry n) {
            return m.getKey().compareTo(n.getKey());
        }
    }
OutPut:
2017-09-27=1
2017-09-28=7
2017-09-29=2
2017-09-30=6
  • HashMap(通过value)排序( 把数据放在list里边才可以使用):
 public static Map getSortHashMapByValue(){
        Map map = new HashMap();
        map.put("2017-09-30", "6");
        map.put("2017-09-29", "2");
        map.put("2017-09-28", "7");
        map.put("2017-09-27", "1");

        List> list = new ArrayList>();
        list.addAll(map.entrySet());

        ValueComparator vc = new ValueComparator();//升序
        Collections.sort(list, vc);
        for (Iterator> it = list.iterator();it.hasNext();) {
            System.out.println(it.next());
        }
         return map;
    }

private static class ValueComparator implements
            Comparator> {
        public int compare(Map.Entry m,
                           Map.Entry n) {
            return m.getValue().compareTo(n.getValue());
        }
    }

OutPut:
2017-09-27=1
2017-09-29=2
2017-09-30=6
2017-09-28=7

  • 对象类默认排序是按某个字段,特殊情况才按另外个字段排序:
 /**
 * 苹果类
 */
public class Apple implements Comparable{


    /**
     * 重量
     */
    private Integer weight;
    /**
     * 价格
     */
    private Integer price;

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }

    @Override
    public String toString() {   //重写toString()方法,方面输出
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        sb.append("Apple:(weight:");
        sb.append(weight);
        sb.append(",price:");
        sb.append(price);
        sb.append(")]");
        return sb.toString();
    }

    @Override
    public int compareTo(Apple o) {  //实现内部排序
        return this.price.compareTo(o.getPrice());
    }
}
public class Test {//测试类
    public static void main(String[] args) {
        List apples = new ArrayList<>();
        Random random = new Random(12);
        for (int i = 0; i < 10; i++) {  //生成10个苹果,重量随机生成
            Apple apple = new Apple();
            apple.setWeight(random.nextInt(1000));
            apple.setPrice(random.nextInt(50));
            apples.add(apple);
        }
        for (Apple apple : apples) { //打印10个苹果的顺序
            System.out.println("apple = " + apple);
        }
       Collections.sort(apples);
        //  Collections.sort(apples,(o1,o2)->o1.getWeight().compareTo(o2.getWeight()));
        for (Apple apple : apples) {
            System.out.println(" sort apple = " + apple);
        }
    }
}
//输出
apple = [Apple:(weight:866,price:12)]
apple = [Apple:(weight:556,price:33)]
apple = [Apple:(weight:624,price:11)]
apple = [Apple:(weight:750,price:15)]
apple = [Apple:(weight:596,price:21)]
apple = [Apple:(weight:568,price:22)]
apple = [Apple:(weight:61,price:7)]
apple = [Apple:(weight:695,price:14)]
apple = [Apple:(weight:536,price:31)]
apple = [Apple:(weight:505,price:3)]
 sort apple = [Apple:(weight:505,price:3)]
 sort apple = [Apple:(weight:61,price:7)]
 sort apple = [Apple:(weight:624,price:11)]
 sort apple = [Apple:(weight:866,price:12)]
 sort apple = [Apple:(weight:695,price:14)]
 sort apple = [Apple:(weight:750,price:15)]
 sort apple = [Apple:(weight:596,price:21)]
 sort apple = [Apple:(weight:568,price:22)]
 sort apple = [Apple:(weight:536,price:31)]
 sort apple = [Apple:(weight:556,price:33)]

你可能感兴趣的:(用java的Comparator给JsonArray、TreeMap、HashMap排序)