Stream常见用法:集合中某个属性值最小的元素、集合中某个属性值最大的元素、集合分组并统计数量、集合按指定属性分组
Posted on 2022-04-20 14:53 CN.programmer.Luxh 阅读(809) 评论(0) 编辑 收藏 举报记录Stream对集合常见的几个用法:
测试对象 Order
@Data
@AllArgsConstructor
@ToString
public class Order {
public String userId;
public String orderId;
private Long createTime;
public Long amount;
}
用法
// 测试数据
Order order1 = new Order("u-001", "o-800", 1650435798635L, 101L);
Order order2 = new Order("u-001", "o-801", 1650435838644L, 102L);
Order order3 = new Order("u-002", "o-802", 1650435871646L, 98L);
Order order4 = new Order("u-003", "o-803", 1650435898645L, 220L);
Order order5 = new Order("u-003", "o-804", 1650435917645L, 300L);
List<Order> orderList = Arrays.asList(order1, order2, order3, order4, order5);
// 1. 查询出订单集合中创建时间最小的元素
Optional<Order> minCreateTimeOption = orderList.stream().min(Comparator.comparing(Order::getCreateTime));
if (minCreateTimeOption.isPresent()) {
Order minCreateTimeOrder = minCreateTimeOption.get();
System.out.println(minCreateTimeOrder);
}
// 2. 查询订单集合中最大的创建时间
OptionalLong maxCreateTime = orderList.stream().mapToLong(Order::getCreateTime).max();
System.out.println("最大的创建时间:" + maxCreateTime);
// 3. 统计订单集合每个用户的订单数量
Map<String, Long> groupByUserAndStatNumMap = orderList.parallelStream().collect(Collectors.groupingBy(Order::getUserId, Collectors.counting()));
Iterator<Map.Entry<String, Long>> iterator = groupByUserAndStatNumMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Long> entry = iterator.next();
System.out.println("用户id:"+entry.getKey() + ", 订单数:" + entry.getValue());
}
// 4.按用户分组
Map<String, List<Order>> groupByUserMap = orderList.parallelStream()
.collect(Collectors.groupingBy(Order::getUserId));
// 5. 获取订单集合中的所有用户id
List<String> userIdList = orderList.stream().map(order-> order.getUserId()).collect(Collectors.toList());
// 6.按照订单id收集对象本身
Map<String, Order> orderMap = orderList.stream().collect(Collectors.toMap(Order::getOrderId, order-> order));