Anthony
Anthony

Reputation: 36008

How to get a particular item from the list?

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

Upvotes: 6

Views: 84

Answers (2)

Alejandro Alcalde
Alejandro Alcalde

Reputation: 6220

You could do something like this:

val a = List(1,2,3,4,5)
a.find(_ == 0)

This way, if the filter operation results in an empty list, you will have a None.

In your specific example:

myList1.find(_.id == toFind1.id)

Now you have several options to continue with the operation:

  1. Pattern match on `myList1.find(_.id == toFind1.id)
  2. Get the result inside or provide a default value: myList1.find(_.id == toFind1.id).getOrElse("DefaultValue")
  3. Use other transformations, like myList1.find(_.id == toFind1.id).map(somFunc) etc.

Hope it helps.

Upvotes: 0

Xavier Guihot
Xavier Guihot

Reputation: 61774

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)

Upvotes: 5

Related Questions