java8 将 list 里的数据分组。返回 map 集合。
这里以一个简化了的订单类来说明如何分组
数据实体
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class OrderEntity {
private Integer id;
private String sn;
private Integer status;
}
初始化数据
List<OrderEntity> orderEntities = Lists.newArrayList();
orderEntities.add(new OrderEntity(0,"sn000",0));
orderEntities.add(new OrderEntity(1,"sn001",0));
orderEntities.add(new OrderEntity(2,"sn002",1));
orderEntities.add(new OrderEntity(3,"sn003",1));
可能有这样的需求,查询不同订单状态的统计信息
就是查询出所有的订单 然后计算不同状态有多少个。
Map<Integer,Long> rstMap = orderEntities.stream()
.collect(Collectors.groupingBy(OrderEntity::getStatus,Collectors.counting()));
rstMap.forEach((k,v)-> System.out.println("key - >" + k + " , value -> " + v));
结果如下,状态是0的有2个,状态是1的也有2个
key - >0 , value -> 2
key - >1 , value -> 2
如果是按照订单状态分组,组里面保存完整的订单信息
Map<Integer,List<OrderEntity>> rstMap2 = orderEntities.stream()
.collect(Collectors.groupingBy(OrderEntity::getStatus));
rstMap2.forEach((k,v)-> System.out.println("key - >" + k + " , value -> " + v));
执行结果
key - >0 , value -> [OrderEntity(id=0, sn=sn000, status=0), OrderEntity(id=1, sn=sn001, status=0)]
key - >1 , value -> [OrderEntity(id=2, sn=sn002, status=1), OrderEntity(id=3, sn=sn003, status=1)]