我很惊讶地发现,当我添加过滤器块时,限制块停止工作-流保持无限。 查看示例代码
import org.joda.time.LocalDate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class A {
private static final long MAX_DAYS = 9;
public static void main(String[] args) {
LocalDate startDate = LocalDate.now();
Set<LocalDate> bankWorkDays = new HashSet<>();
bankWorkDays.add(startDate.plusDays(1));
bankWorkDays.add(startDate.plusDays(2));
bankWorkDays.add(startDate.plusDays(4));
bankWorkDays.add(startDate.plusDays(5));
final List<LocalDate> workDays = Stream.iterate(startDate, localDate -> localDate.plusDays(1))
.filter(bankWorkDays::contains)
.limit(MAX_DAYS)
.collect(Collectors.toList());
/*
final List<LocalDate> workDays = new ArrayList<>();
long limit = overdueDaysRange;
for (LocalDate localDate = startDate; ; localDate = localDate.plusDays(1)) {
if (bankWorkDays.contains(localDate)) {
if (limit-- == 0) break;
workDays.add(localDate);
}
}
*/
}
}
在注释块中,我粘贴了当我要求IDE将代码转换为等效循环时生成的代码。
我不明白为什么流不能首先生成值,然后根据需要对其进行过滤,然后进行检查之后,到目前为止流的元素总数仍小于极限值的原因?