java - 操作两个流后无法将结果保存到 List<Long>

标签 java lambda collections

我正在过滤两个流并在中间进行除法,但最后我无法将结果收集到列表中。你能告诉我我做错了什么吗?

这是我的代码

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/

相关文章:

C++ 捕获移动初始化是 const 吗?

generics - Kotlin 中扩展函数的多态性

java - 为什么 List 不简单地定义为抽象类而不是接口(interface)?

java - 无法找到或加载主类 org.apache.hadoop.mapred.YarnChild Hadoop3.0.0

java - 如何从另一个类更改 imageview 源?

java - 没有加密的 sslengine 密码套件

collections - 在 NUnit 中断言集合与预期集合的顺序相同

java - 在 textlocal 上收到错误代码 80

python - 只是用 lambda 尝试/排除 - Python?

c++ - 如何在 C++ 中实现自定义标准集合?