美文网首页
用java的Comparator给JsonArray、TreeM

用java的Comparator给JsonArray、TreeM

作者: 外匹夫 | 来源:发表于2017-10-18 22:19 被阅读0次
    • JsonArray排序:
    public List<JSONObject> getSortJsonList(JSONArray jsonArray){
            List<JSONObject> jsonObjectList=new ArrayList<JSONObject>();
            for(int i=0;i<jsonArray.size();i++){
                JSONObject temp= jsonArray.getJSONObject(i);
                jsonObjectList.add(temp);
            }
            //Lambda表达式 Java编译器可以自动推导出参数类型,所以不用再写一次类型。  下面写法可以用lambda表达式代替
            //Collections.sort(jsonObjectList, (a, b) -> String.valueOf(a.get("day_id")).compareTo(String.valueOf(b.get("day_id"))));//升序
            //老版本的写法
            Collections.sort(jsonObjectList, new Comparator<JSONObject>(){
                @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<String, String> getSortTreeMapByKey(JSONArray jsonArray){
            //下面一段可用lambda表达式代替
            //TreeMap<String, String> map = new TreeMap<String, String>((o1,o2)->o2.compareTo(o1));
            TreeMap<String, String> map = new TreeMap<String, String>(new Comparator<String>(){
                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<String,String> entry:map.entrySet()){
                System.out.println("key:"+entry.getKey()+",:value:"+entry.getValue());
            }
             return map;
        }
    
    • TreeMap(通过value)排序:
     public TreeMap<String, String> getSortTreeMapByValue(JSONArray jsonArray){
            TreeMap<String, String> map = new TreeMap<>();
            map.put("zdef","rfgh");
            map.put("asrg","zfg");
            map.put("rgd","dfgh");
            map.put("cbf","gddf");
            //将Map转为List
            List<Map.Entry<String,String>> list = new ArrayList<>(map.entrySet());
            Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return  o2.getValue().compareTo(o1.getValue());//降序
                }
            });
            //运用lambda表达式
            //Collections.sort(list,((o1, o2) -> o2.getValue().compareTo(o1.getValue())));
            for(Map.Entry<String,String> 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<String, String> map = new HashMap<String, String>();
            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<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>();
            list.addAll(map.entrySet());
    
            KeyComparator kc = new KeyComparator();//升序
            Collections.sort(list, kc);
            for (Iterator<Map.Entry<String, String>> it = list.iterator(); it
                    .hasNext();) {
                System.out.println(it.next());
            }
             return map;
        }
    
    private static class KeyComparator implements
                Comparator<Map.Entry<String, String>> {
            public int compare(Map.Entry<String, String> m,
                               Map.Entry<String, String> 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<String, String> map = new HashMap<String, String>();
            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<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>();
            list.addAll(map.entrySet());
    
            ValueComparator vc = new ValueComparator();//升序
            Collections.sort(list, vc);
            for (Iterator<Map.Entry<String, String>> it = list.iterator();it.hasNext();) {
                System.out.println(it.next());
            }
             return map;
        }
    
    private static class ValueComparator implements
                Comparator<Map.Entry<String, String>> {
            public int compare(Map.Entry<String, String> m,
                               Map.Entry<String, String> 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<Apple>{
    
    
        /**
         * 重量
         */
        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<Apple> 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、TreeM

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