码迷,mamicode.com
首页 > 编程语言 > 详细

java按某个字段对数据分组

时间:2018-07-19 16:06:56      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:stat   fas   sys   disco   bsp   lib   class   imp   min   

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<String, List<?>> groupByCode(String msg) {
        JSONArray data = JSONArray.parseArray(msg);
        Map<String, List<?>> dataMap = new HashMap<String, List<?>>();
        //数据分组算法
        for (int i = 0; i < data.size(); i++) {
            JSONObject json = (JSONObject)data.get(i);
            List<Object> tempList = (List<Object>) 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;
    }

}

 

java按某个字段对数据分组

标签:stat   fas   sys   disco   bsp   lib   class   imp   min   

原文地址:https://www.cnblogs.com/iyyy/p/9335941.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!