Collections · 29 of 42

Collections - Concatenation

  • Arrays, Lists, Maps and Sets can be concatenated using the ++ method
  • You can chain this to concatenate multiple collections, e.g. List(1, 2, 3) ++ List(4, 5, 6) ++ List(7, 8, 9)
  • For Maps, duplicate keys are overwritten (in the result) by the rightmost Map that has them, e.g. Map("key" -> "value") ++ Map("key" -> "value2") will generate a new Map containing Map("key" -> "value2")
  • Concatenation does not modify the collections, it simply generates a new collection that contains all elements of the first collection followed by the elements of the second and so forth

See also

val array = Array(1,2,3)
val list = List(1, 2, 3)
val map = Map("one" -> 1, "two" -> 2, "three" -> 3)
val set = Set(1, 2, 3)

//Concatenating
val arrayConcat = array ++ Array(3, 4, 5)
val listConcat = list ++ List(4, 5, 6)
val mapConcat = map ++ Map("four" -> 4, "five" -> 5, "six" -> 6)

//Legacy ::: operator in Lists only
val listConcat2 = list ::: List(4, 5, 6)

println(arrayConcat.mkString(","))
println(listConcat.mkString(","))
println(listConcat2.mkString(","))
println(mapConcat.mkString(","))

Contents

Scala basics

  1. Overview
  2. Scalculator
  3. Operators are methods
  4. Variables
  5. Final variables
  6. Printing values
  7. String interpolation
  8. String formatting
  9. Useful operations
  10. Method definition
  11. Method definition 2
  12. Method definition 3
  13. Anonymous functions
  14. Anonymous functions 2
  15. Return multiple values
  16. Declare multiple variables
  17. Assign multiple variables
  18. Loops using while
  19. Loops using for
  20. Loops without loops
  21. If
  22. Match as a switch
  23. Arrays
  24. Lists
  25. Sets
  26. Maps
  27. Mutable collections
  28. Collections: accessing elements
  29. Collections: concatenation
  30. Mutable collection operations
  31. Immutable collections with var
  32. Collections: useful methods
  33. Classes
  34. Classes, continued

What's new in Scala 3

  1. Scala 3: what changed
  2. Optional braces & new control syntax
  3. Top-level definitions & @main
  4. Enums & ADTs
  5. Extension methods
  6. given & using
  7. Union & intersection types
  8. Smaller niceties