使用java8的语法将List<Object>组装成Map, key为Object里的主键(一对多)
List<Order> orderList ; //伪代码 表示下类型
//组装成返回结构
//key:orderId value:SimpleOrderList
Map<Integer, List<SimpleOrder>> map = orderList.stream().collect(Collectors.toMap(Order::getOrderId,
new Function< Order, List< SimpleOrder >>() {
@Override
public List< SimpleOrder > apply(Order order) { return Lists.newArrayList(new SimpleOrder(order.getOrderId(), order.getUserId())); }
},
(l1, l2) -> { if (l1.size() < limitNum) {l1.addAll(l2);} return l1; }
));
value非List的情况
List<Order> orderList ;
Map<Integer, Order > map = orderList.stream().collect(Collectors.toMap(Order::getSellerId, item -> item));
从List中取其中的属性组成Map
List<Order> orderList ;
List<Integer> sellerIds = orderList.stream().map(Order::getSellerId).collect(Collectors.toList());
List的BigDecimal属性求最大值/最小值/求和/求平均值
//求最大值
BigDecimal max = userList.stream().map(User::getWeight).max((x1, x2) -> x1.compareTo(x2)).get();
//求最小值
BigDecimal min = userList.stream().map(User::getWeight).min((x1, x2) -> x1.compareTo(x2)).get();
//求和
BigDecimal sum = userList.stream().map(User::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
//求平均值
BigDecimal average = userList.stream().map(User::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(userList.size()), 2, BigDecimal.ROUND_HALF_UP);
分组统计BigDecimal类型的数据
Map<String, BigDecimal> specGroup = pageList.stream().collect(Collectors.groupingBy(i -> i.getSpec(), Collectors.reducing(BigDecimal.ZERO, ShipmentOutEntity::getNetWeight, BigDecimal::add)));