-2
A = ... //tuples of Medication(patientid,date,medicine)
B = A.groupby(x => x.patientid)

Example B would look like below - now I need to find the minimum date, how to do that in scala??

(
  478009505-01,
  CompactBuffer(
    Some(Medication(478009505-01,Fri Jun 12 10:30:00 EDT 2009,glimepiride)), 
    Some(Medication(478009505-01,Fri Jun 12 10:30:00 EDT 2009,glimepiride)),
    Some(Medication(478009505-01,Fri Jun 12 10:30:00 EDT 2009,glimepiride))
  )
)
soote
  • 3,240
  • 1
  • 23
  • 34

1 Answers1

0

Making some assumptions on the types:

case class Medication(id: Int, date: String, medicine: String)

val l = List(
  Some(Medication(478009505, "Fri Jun 12 10:30:00 EDT 2010", "glimepiride")),
  Some(Medication(478009505, "Fri Jun 12 10:30:00 EDT 2008", "glimepiride")),
  None,
  Some(Medication(478009505, "Fri Jun 12 10:30:00 EDT 2011", "glimepiride"))
)

You can use a for comprehension to extract all the dates, then get the min with minBy:

import java.text.SimpleDateFormat
val format = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy")
def createDateTime(s: String) = new Date(format.parse(s).getTime))

val dates = for { 
    optMed <- l                  // foreach item
    med <- optMed                // if it contains some value
} yield createDateTime(med.date) // create a comparable date

dates.minBy(_.getTime)           // get the minimum date

The result is the oldest date(2008-06-12)

soote
  • 3,240
  • 1
  • 23
  • 34
  • 1
    That looks pretty good. I'd recommend using .flatMap instead of `filter(_.isDefined)` and `map`. Also sorting and taking the first element is not as efficient as `minBy`, which runs in O(n) time instead of O(n*logn). Try: `l.flatMap(x => new Date(...)).minBy(_.getTime)` – Sohan Jain Feb 27 '16 at 04:31
  • thanks for minBy, didn't know about those. If I use flatMap, I get NoSuchElements for the Nones? – soote Feb 27 '16 at 04:36
  • 1
    Ah woops, you're right; my mistake. It'd have to be `l.flatMap(_.map(x => new Date(...)))`. `flatMap` is like `map` and then `flatten` in this case – Sohan Jain Feb 27 '16 at 04:54
  • I like that better since the compiler knows the x isn't an option, but it's slightly less readable. I guess it's scala, so compiler safety wins. – soote Feb 27 '16 at 04:58
  • 1
    Yep I definitely agree the `flatMap(_.map` is less readable. And as you say, it's nice avoid using `.get`, because if someone removes the `_.isDefined` bit, we'll get a runtime error instead of compile-time. Maybe we can make it more readable by naming our variables: `l.flatMap(dateOption => dateOption.map(x => new Date(format.parse(x.date).getTime)))`? (I'm just splitting hairs for conversations' sake here) – Sohan Jain Feb 27 '16 at 05:03
  • perhaps a for comprehention: val dates = for { optMed <- l med <- optMed } yield new Date(med.date) – soote Feb 27 '16 at 05:15