美文网首页
日拱一卒:Lamdba 之查找和匹配

日拱一卒:Lamdba 之查找和匹配

作者: Tinyspot | 来源:发表于2023-10-15 09:56 被阅读0次

    1. 查找元素

    public interface Stream<T> extends BaseStream<T, Stream<T>> {
        Optional<T> findAny();
        Optional<T> findFirst();
    }
    

    1.1 findAny

    @Test
    public void findAny() {
        List<OrderDTO> orders = Stream.of(new OrderDTO("A001", "1001", 0),
                        new OrderDTO("A002", "1002", 1),
                        new OrderDTO("A003", "1003", 1))
                .collect(Collectors.toList());
    
        OrderDTO orderDTO = orders.stream()
                .filter(order -> order.getOrderStatus() == 1)
                .findAny()  // or .findFirst()
                .orElse(null);
    }
    

    抛异常方式

    OrderDTO orderDTO1 = orders.stream()
            .filter(order -> order.getOrderStatus() == 1)
            .findAny()
            .orElseThrow(() -> new RuntimeException("No match found"));
    

    2. match匹配

    public interface Stream<T> extends BaseStream<T, Stream<T>> {
        boolean anyMatch(Predicate<? super T> predicate);
        boolean allMatch(Predicate<? super T> predicate);
        boolean noneMatch(Predicate<? super T> predicate);
    }
    

    2.1 checkNull

    @Test
    public void checkNull() {
    
        List<OrderItemDTO> orderItems = Stream.of(new OrderItemDTO()).collect(Collectors.toList());
        
        // 判断 goodsId 是否为空
        boolean anyMatch = Optional.ofNullable(orderItems)
                .orElse(Collections.emptyList())
                .stream()
                .map(OrderItemDTO::getGoodsId)
                .anyMatch(StringUtils::isEmpty);
        // StringUtils::isEmpty 等价:str -> StringUtils.isEmpty(str)
    
        // 判断 OrderItemDTO 是否为Null
        boolean anyMatch1 = Optional.ofNullable(orderItems)
                .orElse(Collections.emptyList())
                .stream()
                .anyMatch(Objects::isNull);
    }
    

    2.2 anyMatch

    @Test
    public void anyMatch() {
        List<OrderDTO> orders = Stream.of(new OrderDTO("A001", "1001", 0),
                        new OrderDTO("A002", "1002", 1),
                        new OrderDTO("A003", "1003", 1))
                .collect(Collectors.toList());
    
        boolean present = orders.stream()
                .filter(order -> order.getOrderStatus() == 1)
                .findAny()
                .isPresent();
        // 等价
        boolean anyMatch = orders.stream().anyMatch(orderDTO -> orderDTO.getOrderStatus() == 1);
    
        boolean allMatch = orders.stream().allMatch(orderDTO -> orderDTO.getOrderStatus() == 1);
    
        boolean noneMatch = orders.stream().noneMatch(orderDTO -> orderDTO.getOrderStatus() == 1);
    }
    

    相关文章

      网友评论

          本文标题:日拱一卒:Lamdba 之查找和匹配

          本文链接:https://www.haomeiwen.com/subject/ovdtidtx.html