Scala List FAQ: Can you share some Scala List class examples?

The Scala List class may be the most commonly used data structure in Scala applications. Therefore, it's very helpful to know how create lists, merge lists, select items from lists, operate on each element in a list, and so on.

In this tutorial, I'll try to share examples of the most common List operations (methods).

1) Scala List class - Introduction

The Scala List class (scala.List) holds a sequenced, linear list of items. In a List, each element must be of the same type.

At some point I'll add a class diagram here, but until then, here's a simplified version of the Scala List class hierarchy:

  • The scala.List class is a pointer to the scala.collection.immutable.List class.
  • The List class extends LinearSeq with Product (and some others).
  • The trait LinearSeq extends Seq
  • The trait Seq extends Iterable
  • Iterable extends trait Traversable

(I need to update this, but this is the Scala class hierarchy, as shown by thecurrent Scala API documentation.

2) Creating a Scala List object

You can create a Scala List object in several different way. Here's the Lisp-style approach to creating a List:

  1. scala> val list = 1 :: 2 :: 3 :: Nil
  2. list: List[Int] = List(1, 2, 3)

Here's the Java-style approach to creating a Scala List:

  1. scala> val list = List(1,2,3)
  2. x: List[Int] = List(1, 2, 3)

A few notes about these approaches:

  • The first approach shows the "cons" syntax, which, as I mentioned, is the Lisp style of creating a list.
  • The :: method takes two arguments, a "head", which is a single element, and a "tail", which is a List.
  • As you can see, Scala can usually infer the type of a List very well.

If you're mixing types in a List constructor, you may need to manually specify the List type. This example demonstrates that syntax:

  1. scala> val x = List[Number](1, 2.0, 33d, 0x1)
  2. x: List[java.lang.Number] = List(1, 2.0, 33.0, 1)

In this example, I'm explicitly saying that I want the values in the List to be saved as the Number type.

2.1) The List range method

You can also create a List with the List's range method:

  1. scala> val x = List.range(1,10)
  2. x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

The range function can also take a third argument which serves as a "step" value when creating the List:

  1. scala> val x = List.range(0,10,2)
  2. x: List[Int] = List(0, 2, 4, 6, 8)

2.2) The List fill method

You can also create a new List with the fill method:

  1. scala> val x = List.fill(3)("foo")
  2. x: List[java.lang.String] = List(foo, foo, foo)

2.3) The List tabulate method

Finally, you can create a new List with the tabulate method of the List class. The tabulate method creates a new List whose elements are created according to the function you supply. The book Programming in Scala shows how to create a List using a simple "squares" function:

  1. scala> val x = List.tabulate(5)(n => n * n)
  2. x: List[Int] = List(0, 1, 4, 9, 16)

As you can see, that example creates a List of five elements, where the element values are the square of the index of each element (0 becomes 0, 1 becomes 1, 2 becomes 4, 3 becomes 9, and 4 becomes 16).

In summary, you can create a new Scala List with these approaches:

  • Lisp style
  • Java style
  • range method
  • tabulate method

3) Prepend items to a List

You can prepend items to a Scala List using the :: method:

  1. // create a List
  2. scala> val x = List(1,2,3)
  3. x: List[Int] = List(1, 2, 3)
  4.  
  5. // prepend an element to the list
  6. scala> val y = 0 :: x
  7. y: List[Int] = List(0, 1, 2, 3)

According to the Beginning Scala book (and several other sources), prepending items to a list is a "very fast, constant-time, O(1) operation."

(Again, I recall this approach and syntax from using Lisp many years ago.)

4) Appending and merging Lists

There are at least two ways to merge Scala Lists. First, you can merge two Scala lists using the ::: method of the List class:

  1. scala> val a = List(1,2,3)
  2. a: List[Int] = List(1, 2, 3)
  3.  
  4. scala> val b = List(4,5,6)
  5. b: List[Int] = List(4, 5, 6)
  6.  
  7. scala> val c = a ::: b
  8. c: List[Int] = List(1, 2, 3, 4, 5, 6)

This operation is said to have O(n) speed, where n is the number of elements in the first List.

You can also merge two Scala lists using the List's concat method:

  1. scala> val a = List(1,2,3)
  2. a: List[Int] = List(1, 2, 3)
  3.  
  4. scala> val b = List(4,5,6)
  5. b: List[Int] = List(4, 5, 6)
  6.  
  7. scala> val c = List.concat(a, b)
  8. c: List[Int] = List(1, 2, 3, 4, 5, 6)

5) Iterating lists with foreach

A very common way to iterate over Scala lists is with the foreach method. Here's a quote about the foreach method from the book Programming in Scala:

foreach takes a procedure (a function with a result type Unit) as the right operand. It simply applies the procedure to each List element. The result of the operation is again Unit; no list of results is assembled.

Here's a simple example showing how to use the foreach function to print every item in a List:

  1. scala> val x = List(1,2,3)
  2. x: List[Int] = List(1, 2, 3)
  3.  
  4. scala> x.foreach { println }
  5. 1
  6. 2
  7. 3

This next example shows a way to sum all the elements in a list using the foreach method:

  1. scala> var sum = 0
  2. sum: Int = 0
  3.  
  4. scala> val x = List(1,2,3)
  5. x: List[Int] = List(1, 2, 3)
  6.  
  7. scala> x.foreach(sum += _)
  8.  
  9. scala> println(sum)
  10. 6

6) Scala Lists and the for comprehension

The Scala for comprehension is not specific to lists, but is an extremely powerful way to operate on lists. Here's a simple example of how to iterate over a list using the for comprehension:

  1. scala> val names = List("Bob", "Fred", "Joe", "Julia", "Kim")
  2. names: List[java.lang.String] = List(Bob, Fred, Joe, Julia, Kim)
  3.  
  4. scala> for (name <- names) println(name)
  5. Bob
  6. Fred
  7. Joe
  8. Julia
  9. Kim

So far, so good. Now let's add a simple "if" clause to the for comprehension to print only the elements we want to print:

  1. scala> val names = List("Bob", "Fred", "Joe", "Julia", "Kim")
  2. names: List[java.lang.String] = List(Bob, Fred, Joe, Julia, Kim)
  3.  
  4. scala> for (name <- names if name.startsWith("J"))
  5. | println(name)
  6. Joe
  7. Julia

If you already know about the for comprehension, you know that you can add multiple if clauses, and much more functionality. I could easily write an entire tutorial on the Scala for comprehension, so to keep this tutorial short, I'll stop here for now.

Before leaving, I will add these notes however, from the book Programming in Scala:

Scala provides the for comprehension, which provides syntactically pleasing nesting of map, flatMap, and filter ... The for comprehension is not a looping construct, but is a syntactic construct the compiler reduces to map, flatMap, and filter.

7) Filtering Scala lists

A great thing about Scala is that it is a functional programming language. In the next examples we'll show some of the power of functional programming. In this section we'll focus on the filter method of the List class.

  1. scala> val x = List(1,2,3,4,5,6,7,8,9,10)
  2. x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  3.  
  4. // create a list of all the even numbers in the list
  5. scala> val evens = x.filter(a => a % 2 == 0)
  6. evens: List[Int] = List(2, 4, 6, 8, 10)

takeWhile

  1. scala> val x = List(1,2,3,4,5,6,7,8,9,10)
  2. x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  3.  
  4. scala> val y = x.takeWhile(a => a < 6)
  5. y: List[Int] = List(1, 2, 3, 4, 5)

Other list filtering methods:

  1. partition - returns a pair of lists, one where the predicate is true,
  2. the other where the predicate is false
  3. find - returns the first element matching a predicate (as opposed to
  4. returning all such elements)
  5.  
  6. Others: takeWhile, dropWhile, span

8) The List map function

The Scala List map function "transforms each element of a collection based on a function."

Here are a few map examples. First, doubling every item in a List:

  1. scala> val x = List(1,2,3)
  2. x: List[Int] = List(1, 2, 3)
  3.  
  4. scala> val y = x.map(a => a * 2)
  5. y: List[Int] = List(2, 4, 6)

Here's a slightly simpler version of that map example, using the Scala wildcard character (_) instead of a fake variable name:

  1. scala> val y = x.map(_ * 2)
  2. y: List[Int] = List(2, 4, 6)

Here's an example using a list of strings:

  1. scala> val names = List("Fred", "Joe", "Bob")
  2. names: List[java.lang.String] = List(Fred, Joe, Bob)
  3.  
  4. scala> val lower = names.map(_.toLowerCase)
  5. lower: List[java.lang.String] = List(fred, joe, bob)
  6.  
  7. scala> val upper = names.map(_.toUpperCase)
  8. upper: List[java.lang.String] = List(FRED, JOE, BOB)

A very nice example in the book Beginning Scala demonstrates how to convert a List into something useful in the HTML world, a list of <li> elements using the map function:

  1. scala> val names = List("Fred", "Joe", "Bob")
  2. names: List[java.lang.String] = List(Fred, Joe, Bob)
  3.  
  4. scala> val li = names.map(name => <li>{name}</li>)
  5. li: List[scala.xml.Elem] = List(<li>Fred</li>, <li>Joe</li>, <li>Bob</li>)

As you can see, you can rapidly build a lot of functionality in just a little bit of code.

9) Sorting Scala Lists

I need to research why this code is deprecated, but for the time being, here's an example of how to sort a Scala List:

  1. scala> val x = List(10, 2, 5)
  2. x: List[Int] = List(10, 2, 5)
  3.  
  4. scala> val y = x.sort(_ < _)
  5. warning: there were 1 deprecation warnings; re-run with -deprecation for details
  6. y: List[Int] = List(2, 5, 10)

(TODO: Research the correct, current approach for sorting Scala lists.)

10) Scala List class and pattern matching

You can use the List class with the Scala pattern matching and case/match syntax. I'll add examples here as I create them in my own code. (TODO)

11) Other Scala List functions

The Scala List class has an incredible number of functions/methods, and over time I'll attempt to document them all. In the meantime, here's a short list of the many other Scala List methods I don't have examples for at this time:

  1. length - returns the length of a List
  2. head - returns the first element of a List
  3. last - returns the last element of a List
  4. init - returns a List consisting of all elements except the last one
  5. tail - returns every elements of a List except the first element
  6. isEmpty - returns a Boolean indicating if the List is empty
  7.  
  8. reverse - returns a reversed version of the List
  9. flatten - takes a list of lists and flattens it out to a single list
  10.  
  11. mkString - converts a List to a String
  12.  
  13. iterator
  14. toArray
  15.  
  16. foldLeft
  17. reduceLeft
  18.  
  19. map
  20. flatMap
  21. foreach
  22.  
  23. forall
  24. exists
  25.  
  26. Folding lists: /: and :\
  27.  
  28. sortWith

Again, I'll try to add examples of these List methods over time. (TODO)

12) Relatives of the Scala List

There are times you may want to use one of the relatives of the Scala List class, instead of using the List class itself. I'll add more to this over time, but for now, here are a few links:

 

Can you share some Scala List class examples?的更多相关文章

  1. How do I add elements to a Scala List?

    Scala List FAQ: How do I add elements to a Scala List? This is actually a trick question, because yo ...

  2. How to add elements to a List in Scala

    Scala List FAQ: How do I add elements to a Scala List? This is actually a trick question, because yo ...

  3. Introducing Apache Spark Datasets(中英双语)

    文章标题 Introducing Apache Spark Datasets 作者介绍 Michael Armbrust, Wenchen Fan, Reynold Xin and Matei Zah ...

  4. How to Use Rsync to Sync New or Changed/Modified Files in Linux

    As a system administrator or Linux power user, you may have probably come across or even on several ...

  5. spark处理jsonFile

    按照spark的说法,这里的jsonFile是特殊的文件: Note that the file that is offered as jsonFile is not a typical JSON f ...

  6. akka简单示例-1

    刚刚开始接触akka,网上找了2个简单示例,并在公司运营机器上尝试,踩了一些坑,在此记录. 1. 本地hello world [torstan@sparkb5-i ~/akka_example/hel ...

  7. Cloudera CDH 5集群搭建(yum 方式)

    1      集群环境 主节点 master001 ~~ master006 从节点 slave001 ~~ slave064 2      安装CDH5的YUM源 rpm -Uvhhttp://ar ...

  8. su鉴定故障

    su切换用户鉴定故障 [yolo1@izqfsfqp8ejn9zz ~]$ su root密码:su: 鉴定故障[yolo1@izqfsfqp8ejn9zz ~]$ sudo root 我们信任您已经 ...

  9. 大数据技术之_19_Spark学习_03_Spark SQL 应用解析 + Spark SQL 概述、解析 、数据源、实战 + 执行 Spark SQL 查询 + JDBC/ODBC 服务器

    第1章 Spark SQL 概述1.1 什么是 Spark SQL1.2 RDD vs DataFrames vs DataSet1.2.1 RDD1.2.2 DataFrame1.2.3 DataS ...

随机推荐

  1. 深入理解索引系列1:B+树

  2. MHDD修复硬盘坏道

    2种修复的方法,本人已经尝试过,非常管用! 1.先按SHIFT+F3扫描硬盘连接并选择,按F4键,先用一般模式扫一遍,再用高级模式扫一变,具体方法是选择LBA模式,remap项OFF,Loop the ...

  3. R语言中数据结构

    R语言还是有点古老感觉,数据结构没有Python中那么好用.以下简单总结一下R语言中经常使用的几个数据结构. 向量: R中的向量能够理解为一维的数组,每一个元素的mode必须同样,能够用c(x:y)进 ...

  4. Linear Algebra Courses

    Lecture 1:Demonstrate the columns of a matrix (imagine the vectors) in N-dimension space.How to mult ...

  5. 【LeetCode】【Python题解】Reverse Integer

    Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123, return -321 click to ...

  6. 转载【TP3.2】:使用PHP生成二维码

    转载:在网上down了一个二维码插件PHPQRcode,整合到了ThinkPHP 3.2.3,然后写了个外部自定义函数直接调用生成二维码,根据参数不同有不同尺寸效果,整合其实挺简单,分享给大家! 今天 ...

  7. HDUOJ---1233还是畅通工程

    还是畅通工程 Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total Subm ...

  8. INFO ipc.Client:Retrying connect to server 9000

    hadoop使用bin/start_all.sh命令之后,使用jps发现datanode无法启动 This problem comes when Datanode daemon on the syst ...

  9. Android之SurfaceView使用总结

    1.概念SurfaceView是View类的子类,可以直接从内存或者DMA等硬件接口取得图像数据,是个非常重要的绘图视图.它的特性是:可以在主线程之外的线程中向屏幕绘图上.这样可以避免画图任务繁重的时 ...

  10. iOS - UnitTests 单元测试

    1.UnitTests 在计算机编程中,单元测试(又称为模块测试, Unit Testing)是针对程序模块(软件设计的最小单位)来进行正确性检验的测试工作.程序单元是应用的最小可测试部件.在过程化编 ...