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 you can‘t add elements to a ScalaList; it‘s an immutable data structure, like a Java String.

Prepending elements to Scala Lists

One thing you can do when working with a Scala List is to create a newList from an existing List. This sort of thing is done often in functional programming, and the general approach looks like this:

scala> val p1 = List("Kim")
p1: List[String] = List(Kim)

scala> val p2 = "Julia" :: p1
p2: List[String] = List(Julia, Kim)

scala> val p3 = "Judi" :: p2
p3: List[String] = List(Judi, Julia, Kim)

Those examples show how to create a series of lists. The initial list namedp1 contains one string, then p2 contains two strings, and finally p3 contains three strings.

While that approach looks cumbersome in a small example, it makes sense in larger, real-world code. You can see more/better examples of this approach in my tutorial titled, Scala List class examples.

Use a ListBuffer when you want a "List" you can modify

If you want to use a Scala sequence that has many characteristics of a Listand is also mutable (you can add and remove elements in it), use theListBuffer class instead, like this:

import scala.collection.mutable.ListBuffer

var fruits = new ListBuffer[String]()
fruits += "Apple"
fruits += "Banana"
fruits += "Orange"

Then convert it to a List if/when you need to:

val fruitsList = fruits.toList

Scala REPL example

Here‘s what this List and ListBuffer example looks like using the Scala command line (REPL):

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> var fruits = new ListBuffer[String]()
fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()

scala> fruits += "Apple"
res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)

scala> fruits += "Banana"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)

scala> fruits += "Orange"
res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)

scala> val fruitsList = fruits.toList
fruitsList: List[String] = List(Apple, Banana, Orange)

More functional ways to work with Scala lists

Depending on your needs, there are other, "more functional" ways to work with Scala lists, and I work through some of those in my Scala List examples. But for my needs today, I just wanted to work with a Scala Listlike I‘d work with a Java List (ArrayListLinkedList), and this approach suits me.

时间: 2024-10-08 21:51:44

How to add elements to a List in Scala的相关文章

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 you can't add elements to a ScalaList; it's an immutable data structure, like a Java String. Prepending elements to Scala Lists One thing you can do whe

select 下拉菜单Option对象使用add(elements,index)方法动态添加

原生js 的add函数为下拉菜单增加选项 1.object.add(oElement [, iIndex]) index 可选参数:指定元素放置所在的索引号,整形值.如果没有指定值,将添加到集合的最后. 想加到最前面,指定索引值0就可以了. @@注意: add方法为js原生方法,属于element元素对象,在使用jquery对象获取元素时是不可用的 var select = $('#select'); select.add(new Option(txt,val)) 提示:undefined ad

collections

1.计数器(counter) Counter是对字典类型的补充,用于追踪值的出现次数. ps:具备字典的所有功能 + 自己的功能 1 c = Counter('abcdeabcdabcaba') 2 print c 3 输出:Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1}) ######################################################################## ### Counter ##

Python之路【第二篇】:Python基础(一)

Python之路[第二篇]:Python基础(一) 入门知识拾遗 一.作用域 对于变量的作用域,执行声明并在内存中存在,该变量就可以在下面的代码中使用. 1 2 3 if 1==1:     name = 'wupeiqi' print  name 下面的结论对吗? 外层变量,可以被内层变量使用 内层变量,无法被外层变量使用 二.三元运算 1 result = 值1 if 条件 else 值2 如果条件为真:result = 值1如果条件为假:result = 值2 三.进制 二进制,01 八进

Map Class Example

Here's a quick look at how to use the Scala Map class, with a colllection of Map class examples. The immutable Map class is in scope by default, so you can create an immutable map without an import, like this: val states = Map("AL" -> "A

How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop?

Scala List/sequence FAQ: How do I iterate over a Scala List (or more generally, a sequence) using theforeach method or for loop? There are a number of ways to iterate over a Scala List using theforeach method (which is available to Scala sequences li

Can you share some Scala List class examples?

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, operat

HashSet vs. TreeSet vs. LinkedHashSet

A Set contains no duplicate elements. That is one of the major reasons to use a set. There are 3 commonly used implementations of Set: HashSet, TreeSet and LinkedHashSet. When and which to use is an important question. In brief, if you need a fast se

jquery 筛选元素 (2)

.add() 创建一个新的对象,元素添加到匹配的元素集合中. .add(selector) selector 一个字符串表示的选择器表达式.找到更多的元素添加到匹配的元素集合. $("p").add("div") .add(html) html HTML片段添加到匹配的元素集合中. $('li').add('<p id="new"> new paragraph</p>') .add(elements) elements 一