2017-07-01 244 views
1

序列最小/最大,我想有一個val the_min,將得到一個序列中的最小值定義爲:斯卡拉找到元組

def datesSequence(): Seq[(String, String, String)] = { 
.... 
} 

由於序列的格式輸出:

println(datesSequence().map { case (y: String, m: String, d: String) => s"$y-$m-$d" } mkString(", ")) 

2017年5月13日,2017年5月12日,2017年5月11日,2017年5月10日,2017年5月9日,2017年5月8日 ,2017年5月7日,2017年-05-06,2017-05-05,2017-05-04, 2017-05-03,... 2017-06-02

我嘗試具有簡單的減少對這樣的結構以獲得最小或最大沒有工作..

用於上述例子中的所希望的輸出(2017年5月13日和2017/06之間的日期/ 02)將是: 分鐘:20170513 最大:20170601

感謝

+1

你爲什麼不嘗試工作?問題是什麼? – Dima

回答

3

現在的元組進行yyyyMMdd形式,你可以得到最小值:

datesSequence().minBy(_.toString) 

作爲一個側面說明,而這是給定條件的快速和骯髒的解決方案,想想代表您的日期是真實Date

2

如果我正確理解你的問題,你可以簡單地應用min,max添加到您提供的日期字符串列表中(如果格式正確)在填充yyyymmdd格式):

val dateSeq: Seq[(String, String, String)] = Seq(
    ("2017", "5", "16"), 
    ("2017", "6", "1"), 
    ("2017", "5", "13"), 
    ("2017", "5", "28"), 
    ("2017", "6", "2"), 
    ("2017", "5", "20"), 
    ("2017", "5", "25") 
) 

// Not needed if month and day in the source list were already properly padded 
def padded(s: String) = if (s.length < 2) "0" + s else s 

val formatedDateSeq = dateSeq.map{ case (y, m, d) => y + padded(m) + padded(d) } 

formatedDateSeq.max 
// res1: String = 20170602 

formatedDateSeq.min 
// res2: String = 20170513 
1

真的很簡單。只需告訴minBy()maxBy()方法如何測量元組。

dateSeq.minBy(x => x._1+x._2+x._3) //res0: (String, String, String) = (2017,05,03) 
dateSeq.maxBy(x => x._1+x._2+x._3) //res1: (String, String, String) = (2017,06,02) 
+0

爲什麼不只是'dateSeq.min','dateSeq.max'?如果你非常渴望爲他做家庭作業,那麼你至少可以向他展示如何一次完成。 – Dima