List<Object> 如何转为Map<String,Map<String,Integer>>
需求:统计不同省下面不同状态的总数量。
先定义一个对象,对象中有省,市,地区,状态,数量五个字段
> public class DTO {
> private String provinceName;
> private String CityName;
> private String codeName;
> private String packstatus;
> private Integer cout; }
设计想要的map,用map<String,map<String,Integer>>,key代表省,value中的key代表状态,value中的value代表数量。
public class test {
public static void main(String[] args) {
//用一些假数据
DTO dto1 = new DTO("河南", "信阳", "息县", "出货", 10);
DTO dto2 = new DTO("河南", "信阳", "云县", "出货", 20);
DTO dto3 = new DTO("河南", "信阳", "是县", "进货", 20);
DTO dto4 = new DTO("浙江", "杭州", "萧山", "进货", 20);
DTO dto5 = new DTO("湖北", "武汉", "远山", "进货", 20);
DTO dto6 = new DTO("江苏", "南京", "玄武", "进货", 20);
//创建arraylist集合
ArrayList<DTO> dtos = new ArrayList<DTO>();
dtos.add(dto1);
dtos.add(dto2);
dtos.add(dto3);
dtos.add(dto4);
dtos.add(dto5);
dtos.add(dto6);
//设计想要的map,key代表省,value再用一个map表示,value中的key代表状态,value中的value代表数量
HashMap<String, Map<String, Integer>> result = new HashMap<String, Map<String, Integer>>();
//对ArrayList集合进行遍历 得到想要的数据
for (DTO dto : dtos) {
String provinceName = dto.getProvinceName(); //省
String cityName = dto.getCityName(); //市
String codeName = dto.getCodeName(); //地区
String status = dto.getPackstatus(); //状态
Integer tempCount = dto.getCout(); //数量
//先进行判断,如果是相同的省 ,在对状态进行判断;不是就创建一个新的key
//jdk1.8特性进行map的key是否相同判断 得到key
boolean contains = result.containsKey(provinceName);
if (contains){
Map<String, Integer> stringIntegerMap = result.get(provinceName);//
// 得到状态(也就是value中的key)对状态进行判断 有的话统计数量
boolean containsKey = stringIntegerMap.containsKey(status);
if(containsKey){
//得到之前的数量
Integer cout = stringIntegerMap.get(status);
cout += tempCount;
HashMap<String, Integer> stringIntegerHashMap = new HashMap<String, Integer>();
stringIntegerHashMap.put(status,cout);
result.put(provinceName,stringIntegerHashMap);
}else {
//map是键值对形式 一个key只能对应一个value
stringIntegerMap.put(status,tempCount);
result.put(provinceName,stringIntegerMap); //进行put操作
}
}else {
HashMap<String, Integer> stringIntegerHashMap = new HashMap<String, Integer>();
stringIntegerHashMap.put(status,tempCount);
result.put(provinceName,stringIntegerHashMap);
}
}
//遍历result 键值对遍历得对象
Set<Map.Entry<String, Map<String, Integer>>> entrySet = result.entrySet();
for (Map.Entry<String, Map<String, Integer>> stringMapEntry : entrySet) {
System.out.println(stringMapEntry);
System.out.println("----");
//对value进行遍历
/* Map<String, Integer> value = stringMapEntry.getValue();
Set<Map.Entry<String, Integer>> entries = value.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
System.out.println(entry);
System.out.println("====");
}*/
}
}
}
测试下结果