业务场景:
在List<Map<String, Object>>。里面的Map<String, Object>某一个key(订单号)会出现相同。我们需要对相同的key进行合并
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | package com.chinajey.web.test; import java.util.*; /** * Created by water on 2018/11/1. */ public class Test { public static void main(String[] args) { List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> map1 = new HashMap<>(); map1.put( "bar_code" , "java1" ); map1.put( "order_id" , "JAVA交流" ); map1.put( "count" , 1 ); Map<String, Object> map2 = new HashMap<>(); map2.put( "bar_code" , ".net1" ); map2.put( "order_id" , ".NET交流" ); map2.put( "count" , 1 ); Map<String, Object> map3 = new HashMap<>(); map3.put( "bar_code" , "java2" ); map3.put( "order_id" , "JAVA交流" ); map3.put( "count" , 1 ); Map<String, Object> map4 = new HashMap<>(); map4.put( "bar_code" , "java3" ); map4.put( "order_id" , "JAVA交流" ); map4.put( "count" , 1 ); list.add(map1); list.add(map2); list.add(map3); list.add(map4); list = removeRepeatMapByKey(list, "order_id" ); System.out.println(list); } /** * List<Map<String, Object>> key相同累加数量 * @author shijing * @param list * @param mapKey * @return */ public static List<Map<String, Object>> removeRepeatMapByKey(List<Map<String, Object>> list, String mapKey) { //把list中的数据转换成msp,去掉同一id值多余数据,保留查找到第一个id值对应的数据 List<Map<String, Object>> listMap = new ArrayList<>(); Map<String, Map> msp = new HashMap<>(); for ( int i = list.size() - 1 ; i >= 0 ; i--) { Map map = list.get(i); String id = (String) map.get(mapKey); map.remove(mapKey); //记录存在 if (msp.containsKey(id)){ //当前存放的数据 记录存在的数量+当前需要存放的数量 map.put( "count" , Double.parseDouble(msp.get(id).get( "count" ).toString())+Double.parseDouble(map.get( "count" ).toString())); map.put( "bar_code" , msp.get(id).get( "bar_code" ).toString()+ ";" +map.get( "bar_code" ).toString()); } //map 同一个key赋值会替换 msp.put(id, map); } //把msp再转换成list,就会得到根据某一字段去掉重复的数据的List<Map> Set<String> mspKey = msp.keySet(); for (String key : mspKey) { Map newMap = msp.get(key); newMap.put(mapKey, key); listMap.add(newMap); } return listMap; } } |
bar_code相当于订单的批次号,相同订单批次号用;隔开count相当于订单的数量,相同订单号的数量累加
本文为程序员之家原创文章,转载无需和我联系,但请注明来自程序员之家www.baldhome.com