统计表打印

统计表的格式如下


产品1 产品2
产品3
公司1 2 3 4
公司2
0 0 9
总计 2 3 13
代码如下

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class Test2 {


public static void main(String[] args) {


/**获取产品名称列表**/
List<String> productNameList = new ArrayList<>();
productNameList.add("产品1");
productNameList.add("产品2");
productNameList.add("产品3");


/**获取公司下,哪些产品有多少订单数**/
Map<String, Map<String, Integer>> map = new HashMap<>();
Map<String, Integer> company1 = new HashMap<>();
company1.put("产品1", 3);
company1.put("产品3", 10);
Map<String, Integer> company2 = new HashMap<>();
company2.put("产品2", 13);
company2.put("产品3", 8);
map.put("公司1", company1);
map.put("公司2", company2);
System.out.println(map);


/***map的转化**/
Map<String, List<Integer>> result = new HashMap<>();
Iterator<Map.Entry<String, Map<String, Integer>>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Map<String, Integer>> entry = it.next();
List<Integer> list = new ArrayList<>();
for (String s : productNameList) {
Map<String, Integer> productMap = entry.getValue();
if (productMap.containsKey(s)) {// 如果包含了对应产品名称,则用map中的个数
list.add(productMap.get(s));
} else {
list.add(0);
}
}
result.put(entry.getKey(), list);
}
System.out.println(result);


/***统计每个产品的订单数**/
LinkedHashMap<String, Integer> productCountMap = new LinkedHashMap<>();
for (String productName : productNameList) {
productCountMap.put(productName + "count", 0);
}
Iterator<Map.Entry<String, List<Integer>>> it2 = result.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry<String, List<Integer>> entry = it2.next();
List<Integer> list = entry.getValue();
for (int i = 0; i < list.size(); i++) {
Integer num = productCountMap.get(productNameList.get(i) + "count");
num = num + list.get(i);
productCountMap.put(productNameList.get(i) + "count", num);
}
}
System.out.println(productCountMap);


/***统计总数**/
Iterator<Map.Entry<String, List<Integer>>> it1 = result.entrySet().iterator();
Integer count = 0;
while (it1.hasNext()) {
Map.Entry<String, List<Integer>> entry = it1.next();
List<Integer> list = entry.getValue();
for (Integer num : list) {
count = count + num;
}
}
System.out.println(count);


}

}

运行结果

{公司2={产品3=8, 产品2=13}, 公司1={产品1=3, 产品3=10}}
{公司2=[0, 13, 8], 公司1=[3, 0, 10]}
{产品1count=3, 产品2count=13, 产品3count=18}

34

附:list转map

//List转map,因为map是无序的,list转成map后会改变原来的顺序,故转换成LinkedHashMap
//转换成LinkedHashMap后,产品名对应的值是0,代表订单数是0
public LinkedHashMap<String, Integer> listToMap(List<String> list) {
LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
if (list != null) {
for (int i = 0; i < list.size(); i++) {
String value = list.get(i);
map.put(value, 0);
}
}


return map;
}

猜你喜欢

转载自blog.csdn.net/beidaol/article/details/80732935