Scala在元组序列中找到min / max

时间:2017-07-01 20:55:21

标签: scala max min reduce

我希望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-05-13,2017-02-13,2017-05-11,2017-05-10,2017-05-09,   2017-05-08,2017-05-07,2017-05-06,2017-05-05,2017-05-04,   2017-05-03,... 2017-06-02

我尝试简单地减少这种结构以获得最小值或最大值不起作用..

上述示例(2017/05/13和2017/06/02之间的日期)的期望输出将是: min :20170513 max :20170601

感谢

3 个答案:

答案 0 :(得分:3)

现在元组形成datesSequence().minBy(_.toString) 形式,您可以通过以下方式获得最小值:

Date

作为旁注,虽然这是一个具有给定条件的快速解决方案,但请考虑将日期表示为真[__PageA__](PageA.md) [__PageB__](PageB.md)

答案 1 :(得分:2)

如果我正确理解了您的问题,您只需将minmax应用于所提供的日期字符串列表(如果格式正确(例如以填充的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

答案 2 :(得分:1)

非常简单。只需告诉retval = array(); foreach get_branch() as branch if (branch->get_tree()->lookup(name)) { retval[] += branch->get_name(); } } minBy()方法如何衡量元组。

maxBy()