【问题标题】:Difference between fields of tail and head sub-lists of the list: java.lang.IndexOutOfBoundsException: 0列表的tail和head子列表的字段之间的差异:java.lang.IndexOutOfBoundsException:0
【发布时间】:2016-08-25 13:46:58
【问题描述】:

我有RDD[(String,Map[String,List[Product with Serializable]])],如:

(1566,Map(data1 -> List(List(1469785000, 111, 1, 3, null, 0),List(1469785022, 111, 1, 3, null, 0)), data2 -> List((4,88,1469775603,1,3370,f,537490800,661.09)))

我想创建一个新的 RDD,它将包含 data1 列表的尾部和头部子列表之间的时间差(转换为分钟)。

例如,在上面的数据示例中,这是指1469785022 - 1469785000。

我编写了以下代码,但它失败并出现错误java.lang.IndexOutOfBoundsException: 0。 tail 和 head 似乎没有按预期工作。如何解决这个问题?

  val newRDD = currentRDD.map({
    line => Map(("id",line._1),
                ("duration", (line._2.get("data1").get.tail.productElement(0).toString.toLong -                                        
                              line._2.get("data1").get.head.productElement(0).toString.toLong) / 60)
               )
      })

【问题讨论】:

    标签: scala apache-spark


    【解决方案1】:

    您在理解什么是head 和什么是tail 方面存在问题。

    Scala 中的List() 对象有一个头部和一个尾部。如果你有这样的列表:

    scala> val list = List(10, 20, 30)
    

    头尾的结构会是这样的:

    scala> list.head
    res0: Int = 10
    scala> list.tail
    res1: List[Int] = List(20, 30)
    

    因此,在您的代码中,当您使用 tail 时,您将使用 List[Int] 对象。您可以像这样使用tail.head 解决:

    line._2.get("data1").get.tail.head.productElement(0).toString.toLong
    

    【讨论】:

    • 那么,tail 指的是列表中的第一个元素,而head 是除了第一个之外的其余元素?
    • 没有。与此相反。 head 是 List 的第一个元素。 tail 是其余的排除第一个。但剩下的就是List()
    • 所以为了计算最后一个和第一个子列表的时间戳之间的差异,我应该应用这样的东西吗? :line._2.get("data1").get.tail.head.productElement(0).toString.toLong - line._2.get("data1").get.head.productElement(0).toString.toLong`
    • 是的!你需要这样做。
    • 不会tail.head 得到第二个元素,但不是最后一个?想象一下,我的列表中有 5 个子列表,而不是我的示例中的 2 个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多