如何从列表中获取特定项目?
我有一个案例类列表.我想从列表中获取特定项目.
I have a list of a case class. I want to get a particular item from the list.
我愿意
myList.filter(_.id == myobject.id)(0)
当 filter
实际返回一些东西时,这会起作用.但是当过滤器不返回任何内容时,我会得到一个索引越界异常.
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
您可以返回一个 Option[Color]
以便优雅地处理无法找到的项目.
You could return an Option[Color]
in order to gracefully handle items that can't be found.
在这种情况下,我建议使用 find
方法如下:
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
如果您希望返回 Color
而不是 Option[Color]
,您可以随时返回默认值,以防找不到 有问题的颜色
:
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)