The Scala List class filter method implicitly loops over the List/Seq you supply, tests each element of the List with the function you supply. Your function must return true or false, and filter returns the list elements where your function returns true.

Note: Even though I use a List in these examples, thefilter method can be used on any Scalasequence, including Array,ArrayBufferListVectorSeq, etc.

Let's look at a few simple examples. In this first example we filter a small list of numbers so that our resulting list only has numbers that are greater than 2:

scala> val nums = List(5, 1, 4, 3, 2)
nums: List[Int] = List(5, 1, 4, 3, 2) scala> nums.filter(_ > 2)
res0: List[Int] = List(5, 4, 3)

Note that in the real world you'd assign the filtered results to a new List, like this:

val originalList = List(5, 1, 4, 3, 2)
val newList = originalList.filter(_ > 2)

This example shows how to get the even numbers from a List using a simple modulus test:

scala> nums.filter(_ % 2 == 0)
res21: List[Int] = List(4, 2)

You can take that example a step further by filtering and then sorting the list:

scala> nums.filter(_ % 2 == 0).sort(_ < _)
warning: there were 1 deprecation warnings; re-run with -deprecation for details
res22: List[Int] = List(2, 4)

1) filter method examples with a List of Strings

Here are two filter method examples with a list of Strings:

val fruits = List("orange", "peach", "apple", "banana")

scala> fruits.filter(_.length > 5)
res21: List[java.lang.String] = List(banana, orange) scala> fruits.filter(_.startsWith("a"))
res22: List[java.lang.String] = List(apple)
 

2) Combining filter, sort, and map

From the excellent book, Beginning Scala, here's a nice combination of theList filter, sort, and map methods:

trait Person {
def first: String
def age: Int
def valid: Boolean
} Returns the first name of 'valid' persons, sorted by age def validByAge(in: List[Person]) =
in.filter(_.valid).
sort(_.age < _.age).
map(_.first)

The following example shows how you can use filter with map to transform the type of data that the expression returns. In this case we'll start with a sequence of Person objects, and transform it into a sequence ofString objects.

We'll start with a simple case class:

scala> case class Person(first: String, last: String, mi: String)
defined class Person

Next, we'll create a little sequence of Person objects:

scala> val fred = Person("Fred", "Flintstone", "J")
fred: Person = Person(Fred,Flintstone,J) scala> val wilma = Person("Wilma", "Flintstone", "A")
wilma: Person = Person(Wilma,Flintstone,A) scala> val barney = Person("Barney", "Rubble", "J")
barney: Person = Person(Barney,Rubble,J) scala> val betty = Person("Betty", "Rubble", "A")
betty: Person = Person(Betty,Rubble,A) scala> val peeps = Seq(fred, wilma, barney, betty)
peeps: Seq[Person] = List(Person(Fred,Flintstone,J), Person(Wilma,Flintstone,A), Person(Barney,Rubble,J), Person(Betty,Rubble,A))

Finally, we'll combine filter and map to get a list of all first names where the last name is "Flintstone":

scala> peeps.filter(_.last == "Flintstone").map(_.first)
res0: Seq[String] = List(Fred, Wilma)

The way this works is:

  • The filter method returns a sequence of Person objects where the last name is "Flintstone".
  • The map method call gets the first name of each Person object. This results in a sequence of strings, where each string is the first name of each person that came out of the filter call.

I initially wrote this as a for/yield loop, but then realized I could write this much more concisely with this approach. At the moment I find the for/yield loop to be more readable, and this to be much more concise.

In my opinion, this code can be made a little more readable by using a variable name in the map expression, as a reminder that you're still dealing with Person objects:

scala> peeps.filter(_.last == "Flintstone").map(person => person.first)
res1: Seq[String] = List(Fred, Wilma)

3) Scala List filter method summary

I hope these filter method examples have been helpful. Here's a quick summary of how the filter method works:

  • filter implicitly loops over a List.
  • filter takes a function as an argument. That function should take one List element as input, perform the test you define, and then return either true or false (a Boolean).
  • filter only returns List elements that match the filtering expression.

Filter method example的更多相关文章

  1. [Javascript] The Array filter method

    One very common operation in programming is to iterate through an Array's contents, apply a test fun ...

  2. XSS过滤JAVA过滤器filter 防止常见SQL注入

    Java项目中XSS过滤器的使用方法. 简单介绍: XSS : 跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets, CSS)的缩 ...

  3. Swift map filter reduce 使用指南

    转载:https://useyourloaf.com/blog/swift-guide-to-map-filter-reduce/ Using map, filter or reduce to ope ...

  4. [译]Javascript数列filter方法

    本文翻译youtube上的up主kudvenkat的javascript tutorial播放单 源地址在此: https://www.youtube.com/watch?v=PMsVM7rjupU& ...

  5. Node.js:Buffer浅谈

    Javascript在客户端对于unicode编码的数据操作支持非常友好,但是对二进制数据的处理就不尽人意.Node.js为了能够处理二进制数据或非unicode编码的数据,便设计了Buffer类,该 ...

  6. java性能调优及问题追踪--Btrace的使用

    在生产环境中经常遇到格式各样的问题,如OOM或者莫名其妙的进程死掉.一般情况下是通过修改程序,添加打印日志:然后重新发布程序来完成.然而,这不仅麻烦,而且带来很多不可控的因素.有没有一种方式,在不修改 ...

  7. 简单介绍一下R中的几种统计分布及常用模型

    统计学上分布有很多,在R中基本都有描述.因能力有限,我们就挑选几个常用的.比较重要的简单介绍一下每种分布的定义,公式,以及在R中的展示. 统计分布每一种分布有四个函数:d――density(密度函数) ...

  8. SQLAlchemy query with OR/AND/like common filters

    http://www.leeladharan.com/sqlalchemy-query-with-or-and-like-common-filters Some of the most common ...

  9. dojo/query源码解析

    dojo/query模块是dojo为开发者提供的dom查询接口.该模块的输出对象是一个使用css选择符来查询dom元素并返回NodeList对象的函数.同时,dojo/query模块也是一个插件,开发 ...

随机推荐

  1. 动态IP或无公网IP时外网訪问内网ORACLE数据库

    ORACLE数据库是应用最多的一个数据库.一般项目应用.将ORACLE部署在内网,内网调用,及运维都仅仅能是内网完毕. 假设ORACLE主机或所在局域网没有固定公网IP,又想在外网对ORACLE进行訪 ...

  2. xcode8 的坑 Info.plist 配置app权限

    好多更新完Xcode8 的小盆友们(我也是小盆友啦),会发现当我们调用系统功能,相册,相机,麦克风等会出现崩溃,而控制台打印出一堆乱七八糟的看不懂的东西,但是最后一句话是有用的,给出了崩溃的原因 啦, ...

  3. 关于DES加密中的 DESede/CBC/PKCS5Padding

    今天看到一段3DES加密算法的代码,用的参数是DESede/CBC/PKCS5Padding,感觉比较陌生,于是学习了一下. 遇到的java代码如下: Cipher cipher=Cipher.get ...

  4. 【面试笔试】Java常见面试笔试总结

    Java 基础 1.有哪些数据类型 Java定义了8种简单类型:byte.short.int.long.char.float.double和boolean. 2.面向对象的语言特征 封装.继承.多态 ...

  5. 29、java中阻塞队列

    阻塞队列与普通队列的区别在于,当队列是空的时,从队列中获取元素的操作将会被阻塞,或者当队列是满时,往队列里添加元素的操作会被阻塞.试图从空的阻塞队列中获取元素的线程将会被阻塞,直到其他的线程往空的队列 ...

  6. JavaScript的技巧和最佳实践

    JavaScript是一个绝冠全球的编程语言,可用于Web开发.移动应用开发(PhoneGap.Appcelerator).服务器端开发 (Node.js和Wakanda)等等.JavaScript还 ...

  7. mybatis&Hibernate区别

    mybatis是一个不完全的orm框架,因为mybatis需要程序员自己写大量的sql,需要程序员对sql的掌握比较高,不过mybatis可以通过xml文件可以灵活的配置要运行的sql语句,将sql与 ...

  8. Java获取资源的路径

    在Java中,有两种路径: 类路径 文件夹路径 使用类路径有两种方式: object.getClass().getResource()返回资源的URL MyClass.class.getResourc ...

  9. 解决ADSL拨号上网错误691:由于域上的用户名和密码无效而拒绝访问

    此错误是发生在我家用一个台式机拨号上网没问题,但笔记本拨号上网就有问题.   问题解决发现是电信初次拨号上网会绑定这个拨号用户的MAC网卡地址,将台式机的MAC地址配置到我的笔记本上就ok了!     ...

  10. linux ---性能监控(工具)

    linux服务器性能监控-nmon Nmon 是一个分析aix和linux性能的免费工具,出自IBM,其采集的数据通过nmon_analyser生成报表 一.下载 官网下载地址 百度网盘 二.运行和使 ...