Scala List filter() 方法示例
filter()方法用于选择列表中满足指定谓词的所有元素。
Method Definition: def filter(p: (A) => Boolean): List[A]
Return Type: It returns a new list consisting all the elements of the list which satisfies the given predicate.
示例 #1:
// Scala program of filter()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a list
val m1 = List(5, 12, 3, 13)
// Applying filter method
val result = m1.filter(_ < 10)
// Displays output
println(result)
}
}
输出:
List(5, 3)
示例 #2:
// Scala program of filter()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a list
val m1 = List(5, 12, 3, 13)
// Applying filter method
val result = m1.filter(_ < 3)
// Displays output
println(result)
}
}
输出:
List()
在这里,由于没有元素满足所述谓词,因此返回一个空列表。