scala - 为什么在reduce结果上collect失败并显示 "error: value collect is not a member of Int"?

标签 scala apache-spark

我正在尝试使用 apache Spark/scala 查找单词数最多的行。我正在 Spark-Shell 中运行该程序。

当我使用以下代码时,我得到正确的输出:

scala> file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b)

但是当我尝试使用以下代码收集结果时出现错误:

scala> file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b).collect()
<console>:30: error: value collect is not a member of Int
              file1.map(line => line.split(" ").size).reduce((a, b) => if (a > b) a else b).collect()

为什么在使用 collect() 操作时出现错误?

最佳答案

reduce是将一系列 T 类型的值减少为 T 类型的单个值的操作。

reduce(f: (T, T) ⇒ T): T Reduces the elements of this RDD using the specified commutative and associative binary operator.

reduce之后,您将得到最终结果(您也可以为其他转换进行collect)。

根据您的情况,分配reduce 的值并检查其类型。它是Int

val result = file1.
  map(line => line.split(" ").size).
  reduce((a, b) => if (a > b) a else b)
// check the type of the value from `reduce`
scala> :type result
Int

reducecollect 非常相似,因为两者都是给你一个值的操作,但collect会给你一个Array[T] ...

collect(): Array[T] Return an array that contains all of the elements in this RDD.

...而减少只是一个值T

关于scala - 为什么在reduce结果上collect失败并显示 "error: value collect is not a member of Int"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44420128/

相关文章:

hadoop - UNION parent rdd and child rdd before action 时会发生什么?

ScalaMock:无法处理参数超过 22 个的方法(目前)

scala - 使用未过滤的解码请求实体

apache-spark - 系统找不到 spark-shell 中指定的路径

hadoop - Spark自定义序列化程序导致ClassNotFound

scala - Spark 在 groupBy/aggregate 中合并/组合数组

scala - 为什么会抛出堆栈溢出异常?

scala - 使用 Scalatra 和 Casbah 进行 CRUD 操作

java - 如何将 scala.List 转换为 java.util.List?

scala - 使用经过身份验证的 Confluent Schema Registry 配置 Spark 结构化流