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

2023-10-15  本文已影响0人  Tinyspot

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);
}
上一篇 下一篇

猜你喜欢

热点阅读