java中list集合存JSONObject对象,遍历list取json相同key中的值相加

List jsonList = new ArrayList();
        JSONObject json1 = new JSONObject();
        json1.put("code", "MX01");
        json1.put("num", "2");
        JSONObject json2 = new JSONObject();
        json2.put("code", "MX01");
        json2.put("num", "3");
        JSONObject json3 = new JSONObject();
        json3.put("code", "MX02");
        json3.put("num", "1");
        JSONObject json4 = new JSONObject();
        json4.put("code", "MX02");
        json4.put("num", "3");
        JSONObject json5 = new JSONObject();
        json5.put("code", "MX04");
        json5.put("num", "3");
        jsonList.add(json1);
        jsonList.add(json2);
        jsonList.add(json3);
        jsonList.add(json4);
        jsonList.add(json5);
        
        System.out.println();
        List jsonList2 = new ArrayList();
        Set set = new  HashSet();
        for(JSONObject json : jsonList){
            String code = json.getString("code");
            set.add(code);
        }
        for(String str : set){
            int num = 0;
            for(JSONObject json : jsonList){
                if(json.getString("code").equals(str)){
                    num += json.getIntValue("num");
                }
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", str);
            jsonObject.put("num", num);
            jsonList2.add(jsonObject);
            System.out.println(str);
        }
        for(JSONObject json : jsonList2){
            System.out.println(json.getString("code")+","+json.getIntValue("num"));
        }

你可能感兴趣的:(java中list集合存JSONObject对象,遍历list取json相同key中的值相加)