Lobsterrrr Lobsterrrr - 1 year ago 108
Scala Question

Find max and min values in List[List[String]] comparing by the 1st element in each sub-list

I have a data structure like

List[(String, List[List[String]])]
. I need to find maximum and minimum value in the
comparing the 1st element in each sub-list:

This is how I do it:

val timestamp_col_ind = 1

val sorted = processed.map(list => (list._1,list._2.sortWith(_.productElement(timestamp_col_ind).toString.toLong < _.productElement(timestamp_col_ind).toString.toLong)))

Then I access maximum and minimum elements using
, correspondingly.

But the problem is that the sub-lists do not get ordered by the 1st element. What am I doing wrong?

Answer Source

Like Alberto mentioned, it is always good to provide a full example to avoid confusion; see http://stackoverflow.com/help/mcve. Here is a solution to what it looks like you want:

// initialise structure
val data = List(("foo", List(List("2", "b", "b"), List("3", "c", "c"), List("1", "a", "a"))))
// sort by long value of first element of sublists
val sortedData = data.map { case (str, lst) => (str, lst.sortBy(_.head.toLong)) }
// get minimum and maximum
val min = sortedData.map { case (str, lst) => (str, lst.head) }
val max = sortedData.map { case (str, lst) => (str, lst.last) }


min: List[(String, List[String])] = List((foo,List(1, a, a)))
max: List[(String, List[String])] = List((foo,List(3, c, c)))

This assumes that the sublists are never empty, i.e. they do have a head

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download