Search code examples
scalaapache-sparkcase-class

compare same case class data from an array


I have a case class as below :

  case class bar(id:String, name : String, gender : String, dob : String)

And sample data as below :

val barList = Array(bar("1", "ABC", "M", "2000-06-06"), 
                    bar("2", "DEF", "F", "2009-11-12"), 
                    bar("1", "GHI", "M", "2002-06-30"), 
                    bar("2", "JKL", "F", "2008-10-30"))

Now I want to get max and min dob of persons name based id

  def getMaxDOBName(id :String) = {  val idarray = barList.groupBy(_.id)(id).sortBy(_.dob); idarray(0).name  }
  def getMinDOBName(id :String) = {  val idarray = barList.groupBy(_.id)(id).sortBy(_.dob); idarray(1).name  }

I am getting below output :

scala> getMaxDOBName("1")
res16: String = ABC                 // wrong 

scala> getMaxDOBName("2")
res17: String = JKL              // wrong

Do I need to convert dob to date format then do sorting, or can we get any simple way ?


Solution

  • Try using maxBy and minBy with filter:

    def getMaxDOBName(id :String) = barList.filter(_.id == id).maxBy(_.dob).name
    

    Also personally I would say that converting string to actual date will be more correct approach in general case.