这是最近遇到的开发需求,调用了两个RPC,一个是查询订单商品的接口,一个是查询佣金的接口(支持批量),先查询订单商品,再按订单编号查询佣金,存在分页的情况。为了优化代码提高查询效率,先批量按订单号查询了佣金存入了Map<订单号,Map<SKU编号,佣金>>。一个SKU商品存在多个佣金,因为商品存在不同状态。比如买了以后发生退货、换货等。
package utils;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
public class MapTest {
public static void main(String[] args) {
List<Order> orderList = getOrderList();
Map<Integer,Map<Integer,Optional<BigDecimal>>> orderMap = new HashMap<>();
for (Order order : orderList){
Map<Integer,Optional<BigDecimal>> skuMap = order.getOrderSkuList().stream().collect(Collectors.groupingBy(OrderSku::getSkuId,Collectors.mapping(OrderSku::getCommission,Collectors.reducing(BigDecimal::add))));
orderMap.put(order.getOrderId(),skuMap);
}
String orderId = "1";
Map<Integer,Optional<BigDecimal>> sku = orderMap.get(orderId);
}
public static List<Order> getOrderList(){
List<Order> orderList = new ArrayList<>();
Order order1 = new Order(1,new BigDecimal("1.0"));
List<OrderSku> orderSkuList1 = new ArrayList<>();
OrderSku orderSku1 = new OrderSku(1001,1,new BigDecimal(1.2));
OrderSku orderSku2 = new OrderSku(1001,1,new BigDecimal(-1));
orderSkuList1.add(orderSku1);
orderSkuList1.add(orderSku2);
order1.setOrderSkuList(orderSkuList1);
Order order2 = new Order(2,new BigDecimal("2.0"));
List<OrderSku> orderSkuList2 = new ArrayList<>();
OrderSku orderSku3 = new OrderSku(2001,1,new BigDecimal(1.2));
OrderSku orderSku4 = new OrderSku(2002,1,new BigDecimal(-1));
orderSkuList2.add(orderSku3);
orderSkuList2.add(orderSku4);
order2.setOrderSkuList(orderSkuList2);
Order order3 = new Order(3,new BigDecimal("3.0"));
List<OrderSku> orderSkuList3 = new ArrayList<>();
OrderSku orderSku5 = new OrderSku(3001,1,new BigDecimal(1.2));
OrderSku orderSku6 = new OrderSku(3002,1,new BigDecimal(-1));
orderSkuList3.add(orderSku5);
orderSkuList3.add(orderSku6);
order3.setOrderSkuList(orderSkuList3);
orderList.add(order1);
orderList.add(order2);
orderList.add(order3);
return orderList;
}
}
坑在这里
这里面什么类型都可以往里面放,往往不小心就会掉坑里了