您的位置:首页 > Web前端 > JavaScript

两个json数组key相同的数据合并,并排序

2016-08-18 17:17 302 查看

JSONObject jo1 = new JSONObject();

jo1.put("month", "2016-03");

jo1.put("sum", "200");

JSONObject jo2 = new JSONObject();

jo2.put("month", "2015-11");

jo2.put("sum", "400");

JSONObject jo3 = new JSONObject();

jo3.put("month", "2015-07");

jo3.put("sum", "300");

        JSONArray ja1 = new JSONArray();

        ja1.add(jo1);

        ja1.add(jo2);

        ja1.add(jo3);

        

        JSONObject jo4 = new JSONObject();

jo4.put("month", "2016-03");

jo4.put("sum", "100");

JSONObject jo5 = new JSONObject();

jo5.put("month", "2016-02");

jo5.put("sum", "200");

JSONObject jo6 = new JSONObject();

jo6.put("month", "2015-09");

jo6.put("sum", "700");

JSONObject jo7 = new JSONObject();

jo7.put("month", "2015-07");

jo7.put("sum", "200");

        JSONArray ja2 = new JSONArray();

        ja2.add(jo4);

        ja2.add(jo5);

        ja2.add(jo6);

        ja2.add(jo7);

        

        JSONArray ja3 = new JSONArray();

        JSONObject jo = new JSONObject();

        for(int i=0;i<ja1.size();i++){

        for(int j=0;j<ja2.size();j++){

        if(ja1.getJSONObject(i).getString("month").equals(ja2.getJSONObject(j).getString("month"))){

        jo.put("month", ja1.getJSONObject(i).getString("month"));

        int sum1=Integer.parseInt(ja1.getJSONObject(i).getString("sum"));

        int sum2=Integer.parseInt(ja2.getJSONObject(j).getString("sum"));

        int sum = sum1+sum2;

        jo.put("sum", sum);

        ja3.add(jo);

        ja1.remove(i);

        ja2.remove(j);

        }

        }

        }

        

        for(int k=0;k<ja1.size();k++){

        ja3.add(ja1.get(k));

        }

        for(int m=0;m<ja2.size();m++){

        ja3.add(ja2.get(m));

        }

        Collections.sort(ja3);

        System.out.println(ja3);

        

        JSONObject temp = null;

        boolean exchange = false;

        for (int i = 0; i < ja3.size(); i++) {

            exchange = false;

            for (int j = ja3.size() - 2; j >= i; j--) {

                if (ja3.getJSONObject(j+1).getString("month").compareTo(

                        ja3.getJSONObject(j).getString("month")) >= 0) {

                    temp = ja3.getJSONObject(j+1);

                    ja3.set(j + 1, ja3.get(j));

                    ja3.set(j, temp);

                    exchange = true;

                }

            }

            if (!exchange)

                break;

        }

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐