我在想,Java 8的stream在空列表上会有什么行为。
List<?> emptyList = new ArrayList<>();
List<?> processedList = emptyList.stream().collect(Collectors.toList());
这会是空列表还是null
?
我知道流进行惰性传播,那么在这种情况下,调用是否会进入collect()
方法,还是仅停留在stream()
方法中?
我在想,Java 8的stream在空列表上会有什么行为。
List<?> emptyList = new ArrayList<>();
List<?> processedList = emptyList.stream().collect(Collectors.toList());
这会是空列表还是null
?
我知道流进行惰性传播,那么在这种情况下,调用是否会进入collect()
方法,还是仅停留在stream()
方法中?
collect
是终端操作,所以必须进行评估。
当用collect(Collectors.toList())
终止一个Stream
流水线时,您总会得到一个输出List
(永远不会得到null
)。如果这个Stream
是空的(无论是因为源流为空还是因为在终端操作之前过滤了所有元素),输出List
也将为空。
public static <T>
Collector<T, ?, List<T>> toList() {
return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
(left, right) -> { left.addAll(right); return left; },
CH_ID);
}
.collect(Collector.of(ArrayList::new, ArrayList::add, (a, b) -> a, a -> null))
(或类似的代码)会返回 null。而 toList()
方法之所以不会返回 null,是因为它会将结果累加到一个新的列表中。 - Andy TurnerCollectors.toList()
,而是尝试更通用地说 .collect()
。 - Vishwa Ratna