案例

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) {
//list模拟数据
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);
// System.out.println(list1);
// [{salesmanId=2, money=20, shopId=1}, {salesmanId=2, money=100, shopId=2}, {salesmanId=2, money=50, shopId=2}]

//list<Map>分组,按超市分组
// Map<String, List<ShopEntity>> mapGroup = list1.stream().collect(Collectors.groupingBy(ShopEntity::getShopId));
Map<String, List<Map>> mapGroup = list1.stream().collect(Collectors.groupingBy(o -> o.get("shopId") + ""));
// System.out.println(mapGroup);
// {1=[{salesmanId=2, money=20, shopId=1}], 2=[{salesmanId=2, money=100, shopId=2}, {salesmanId=2, money=50, shopId=2}]}
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);
}
// System.out.println(listReturn);
// [{salesmanId=2, money=20, shopId=1}, {salesmanId=2, money=150, shopId=2}]

//根据money 倒叙排序
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);
});
// System.out.println(listReturn);
// [{salesmanId=2, money=150, shopId=2}, {salesmanId=2, money=20, shopId=1}]
}
}