如何从列表中获取特定项目? [英] How to get a particular item from the list?

查看:37
本文介绍了如何从列表中获取特定项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个案例类列表.我想从列表中获取特定项目.

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)

这篇关于如何从列表中获取特定项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆