java按某个字段对数据分组
Posted 搬砖真累
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java按某个字段对数据分组相关的知识,希望对你有一定的参考价值。
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按某个字段对数据分组的主要内容,如果未能解决你的问题,请参考以下文章
Flutter如何根据某个值从firebase对列表进行分组
java后台对查询到的商品列表按店铺分组并返回json数据_新手学习