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
| import java.util.*; import java.util.stream.Collectors; public class Test { public static void main(String[] args) { Map map1 = new HashMap(); map1.put("shopId",1); map1.put("salesmanId",2); map1.put("money", 20); Map map2 = new HashMap(); map2.put("shopId",2); map2.put("salesmanId",2); map2.put("money", 100); Map map5 = new HashMap(); map5.put("shopId",2); map5.put("salesmanId",2); map5.put("money", 50); List<Map> list1 = new ArrayList<>(); list1.add(map1); list1.add(map2); list1.add(map5);
Map<String, List<Map>> mapGroup = list1.stream().collect(Collectors.groupingBy(o -> o.get("shopId") + ""));
List<Map> listReturn = new ArrayList<>(); for (String str : mapGroup.keySet()) { List<Map> task1 = mapGroup.get(str); int money = 0; for (Map mm: task1) { money = money + Integer.valueOf(String.valueOf(mm.get("money"))); } Map<String, Object> mapReturn = new HashMap(); mapReturn.put("shopId", task1.get(0).get("shopId")); mapReturn.put("salesmanId", task1.get(0).get("salesmanId")); mapReturn.put("money", money); listReturn.add(mapReturn); }
Collections.sort(listReturn, (o2, o1) -> { Integer shop1 = Integer.valueOf(o1.get("shopId").toString()); Integer shop2 = Integer.valueOf(o2.get("shopId").toString()); return shop1.compareTo(shop2); });
} }
|