Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a particular item from the list?

Tags:

scala

I have a list of a case class. I want to get a particular item from the list.

I do

myList.filter(_.id == myobject.id)(0)

This would work when the filter actually returns something. But when filter doesn't return anything I get an index out of bound exception.

scala> case class Color (id: Int, name: String)
defined class Color
scala> val myList1 = List[Color](Color(1, "red"), Color(2, "green"), Color(3, "blue"))
myList1: List[Color] = List(Color(1,red), Color(2,green), Color(3,blue))
scala> val toFind1 = Color(10, "white")
toFind1: Color = Color(10,white)
scala> myList1.filter(_.id == toFind1.id)(0)
java.lang.IndexOutOfBoundsException: 0
like image 211
Anthony Avatar asked Dec 21 '18 19:12

Anthony


1 Answers

You could return an Option[Color] in order to gracefully handle items that can't be found.

In that case, I'd suggest using the find method as such:

// val colors = List[Color](Color(1, "red"), Color(2, "green"), Color(3, "blue"))
colors.find(_.id == 2)
// Some(Color(2,green))
colors.find(_.id == 5)
// None

If you'd rather return a Color rather than an Option[Color] you can always return a default value in case you can't find the Color in question:

colors.find(_.id == 5).getOrElse(Color(7, "purple"))
// Color(7,purple)
like image 185
Xavier Guihot Avatar answered Oct 23 '22 04:10

Xavier Guihot