如何创建Map的一对键

时间:2015-10-14 18:10:59

标签: scala

例如:

mylist: Map("Start" -> 2015-05-30T00:00:00.000Z, "Daily" -> 2015-06-02T00:00:00.000Z, "Hourly" -> 2015-06-03T08:00:00.000Z, "End" -> 2015-06-04T15:00:00.000Z)

我想输出如下格式:

myout: List( ("Start" -> 2015-05-30T00:00:00.000Z, "Daily" -> 2015-06-02T00:00:00.000Z), ("Daily" -> 2015-06-02T00:00:00.000Z, "Hourly" -> 2015-06-03T08:00:00.000Z), ("Hourly" -> 2015-06-03T08:00:00.000Z, "End" -> 2015-06-04T15:00:00.000) )
OR
myout: List( ("Start", "Daily"), ("Daily", "Hourly"), ("Hourly", "End"))

案例1:始终以“开始”键开始,“开始”键之前的任何内容都会忽略它。最后一个“结束”键相同

 mylist: Map(Hourly -> 2015-06-01T08:00:00.000Z, Start -> 2015-05-30T00:00:00.000Z, Daily -> 2015-06-02T00:00:00.000Z,  End -> 2015-06-04T15:00:00.000Z, Weekly-> 2015-06-05T00:00:00.000Z)

输出应该像:

  List((Start, Daily), (Daily, End))

我正在使用scala查看输出。

2 个答案:

答案 0 :(得分:1)

import scala.collection.immutable.ListMap

val x = ListMap("Start" -> "x", "Daily" -> "y", "Hourly" -> "z", "End" -> "a")

x.toList.sliding(2).map( a => (a(0)._1, a(1)._1)).toList

List((Start,Daily), (Daily,Hourly), (Hourly,End))

答案 1 :(得分:0)

由于未订购Map,我修改了输入数据以获得稳定的结果。

至于第一个问题

val m = 
  Map(
    "1-Start" -> "2015-05-30T00:00:00.000Z", 
    "2-Daily" -> "2015-06-02T00:00:00.000Z", 
    "3-Hourly" -> "2015-06-03T08:00:00.000Z", 
    "4-End" -> "2015-06-04T15:00:00.000Z")

基本思路是zip具有自己尾部的键列表来获取对:

scala> m.keys.toList.sorted.zip(m.keys.toList.sorted.tail)
res57: List[(String, String)] = List((1-Start,2-Daily), (2-Daily,3-Hourly), 
  (3-Hourly,4-End))

简化表达式"管道转发运算符"很有帮助:

object PipeForwardContainer {
  implicit class PipeForward[T](val v: T) extends AnyVal {
    def |>[R](f: T => R): R = {
      f(v)
    }
  }
}

import PipeForwardContainer._

此运算符提供对中间结果的引用。因此你可以写:

scala> m.keys.toList.sorted |> { l => l.zip(l.tail) }
res97: List[(String, String)] = List((1-Start,2-Daily), (2-Daily,3-Hourly), 
  (3-Hourly,4-End))

至于第二个问题

val m = 
  Map(
    "1-Hourly" -> "2015-06-03T08:00:00.000Z", 
    "2-Start" -> "2015-05-30T00:00:00.000Z", 
    "3-Daily" -> "2015-06-02T00:00:00.000Z", 
    "4-End" -> "2015-06-04T15:00:00.000Z",
    "5-Weekly"-> "2015-06-05T00:00:00.000Z")

要获取原始列表,您可以按索引slice输出相关元素:

scala> m.keys.toList.sorted |> { l => 
  l.slice(l.indexOf("2-Start"), l.indexOf("4-End") + 1) }
res96: List[String] = List(2-Start, 3-Daily, 4-End)

再次使用zip获取对:

scala> m.keys.toList.sorted |> { l => 
    l.slice(l.indexOf("2-Start"), l.indexOf("4-End") + 1) 
  } |> { l => l.zip(l.tail) }
res98: List[(String, String)] = List((1-Start,2-Daily), (2-Daily,3-Hourly), 
  (3-Hourly,4-End))