자바 데이터 그룹

4400 단어
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonTest {
    
    public static void main(String[] args) {
        String msg = "[{\"serviceCode\":\"MCY000003\",\"serviceName\":\"   \",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000002\",\"serviceName\":\"   \",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000001\",\"serviceName\":\"   \",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000001\",\"serviceName\":\"   \",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000003\",\"serviceName\":\"   \",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"},{\"serviceCode\":\"MCY000005\",\"serviceName\":\"   \",\"discount_rate\":\"80%\",\"minoutdays\":\"0\",\"maxoutdays\":\"5\"}]";
        groupByCode(msg);
    }

    private static Map> groupByCode(String msg) {
        JSONArray data = JSONArray.parseArray(msg);
        Map> dataMap = new HashMap>();
        //      
        for (int i = 0; i < data.size(); i++) {
            JSONObject json = (JSONObject)data.get(i);
            List tempList = (List) dataMap.get(json.get("serviceCode"));
            if(tempList == null) { //      ,   list
                tempList = new ArrayList<>();
                tempList.add(json);
                dataMap.put(json.get("serviceCode").toString(), tempList);//  map 
            }else {
                tempList.add(json);
            }
        }
        //  
        for (String serviceCode : dataMap.keySet()) {
            System.out.println(serviceCode+":"+dataMap.get(serviceCode));
        }
        return dataMap;
    }

}

 
다음으로 전송:https://www.cnblogs.com/iyyy/p/9335941.html

좋은 웹페이지 즐겨찾기