如何从列表中筛选出无选项? [英] How to filter None's out of List[Option]?
本文介绍了如何从列表中筛选出无选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我在Scala中有一个List[Option[A]]
,那么过滤掉None
值的惯用方式是什么?
If I have a List[Option[A]]
in Scala, what is the idiomatic way to filter out the None
values?
一种方法是使用以下内容:
One way is to use the following:
val someList: List[Option[String]] = List(Some("Hello"), None, Some("Goodbye"))
someList.filter(_ != None)
还有更惯用的方式吗?这看起来确实很简单.
Is there a more "idiomatic" way? This does seem pretty simple.
推荐答案
如果要同时删除这些选项,则可以使用flatten
:
If you want to get rid of the options at the same time, you can use flatten
:
scala> someList.flatten
res0: List[String] = List(Hello, Goodbye)
这篇关于如何从列表中筛选出无选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文