其他分享
首页 > 其他分享> > Stream常见用法:集合创建时间最小的元素、集合中最大的创建时间、集合分组并统计数量、集合按指定属性分组

Stream常见用法:集合创建时间最小的元素、集合中最大的创建时间、集合分组并统计数量、集合按指定属性分组

作者:互联网

记录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));

标签:iterator,创建,public,分组,orderList,集合,new,Order
来源: https://www.cnblogs.com/luxh/p/16169854.html