使用streams.zip方法对localdate对象同时使用两个流

x33g5p2x  于 2021-07-11  发布在  Java
关注(0)|答案(2)|浏览(175)

我需要对作为输入提供给我的两个列表进行流式处理,我想比较两个列表中同一索引处的元素,如果第一个列表的元素总是大于第二个列表的元素,则返回true。我可以使用循环解决问题,但是从美学的Angular 来说,并将代码的可读性牢记在心,我想使用java流。

static boolean validate(List<LocalDate> endDates, List<LocalDate> startDates) {
    //check for all elements if the element in first list is greater than elements in second list.
    //return false if above condition fails.
    Streams.zip(endDate, startDates, (endDate, startDate) -> {..})
}
2fjabf4q

2fjabf4q1#

你可以用 Stream.allMatch 通过对列表元素进行一对一比较:

static boolean validate(List<LocalDate> endDates, List<LocalDate> startDates) {
    return IntStream.range(0, endDates.size())
            .allMatch(i -> endDates.get(i).isAfter(startDates.get(i)));
}

当然,这假设两个列表的长度相同(如果 endDates 短于 startDates ,你有一个错误;如果 startDates 如果时间较短,将在上引发异常 startDates.get(i) )

brvekthn

brvekthn2#

当前的streamapi实现(包括最新版本的java16)没有提供这种方法,您需要使用第三方库,例如streamex和该方法 StreamEx.zip() 或者使用 java.util.IntStream.range 达到同样的效果。但是,您有责任避免索引溢出。
最小样本:

List<LocalDate> one = Arrays.asList(LocalDate.now(), LocalDate.now(), LocalDate.now());
List<LocalDate> two = Arrays.asList(LocalDate.MIN, LocalDate.MIN);

boolean allAfter = IntStream
        .range(0, Math.min(one.size(), two.size()))                 // limit the indices
        .allMatch(index -> one.get(index).isAfter(two.get(index))); // compare the dates

相关问题