我正在过滤两个流并在中间进行除法,但最后我无法将结果收集到列表中。你能告诉我我做错了什么吗?
这是我的代码
List<Long> average_population = total_population.stream()
.flatMapToLong( a-> number_of_cities.stream().mapToLong( b-> b/a ))
.collect(null, Collectors.toList() ); <- error
这是我在最后一行遇到的错误。
The method collect(Supplier, ObjLongConsumer, BiConsumer) in the type LongStream is not applicable for the arguments (null, Collector>) Type mismatch: cannot convert from Collector> to ObjLongConsumer
最佳答案
LongStream.collect
需要 3 个参数。
您可能正在寻找这个:
List<Long> average_population =
total_population.stream()
.flatMapToLong(a -> number_of_cities.stream().mapToLong(b -> b / a))
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
但实际上,坚持Long
并不会给你带来太多好处,
使用flatMap
编写会更简单,
这也将允许您使用更简单的collect
:
List<Long> average_population =
total_population.stream()
.flatMap(a -> number_of_cities.stream().map(b -> b / a))
.collect(Collectors.toList());
关于java - 操作两个流后无法将结果保存到 List<Long>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46673008/