VOOZH about

URL: https://www.geeksforgeeks.org/scala/scala-lists/

⇱ Scala Lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Scala Lists

Last Updated : 14 Mar, 2019
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Following are the point of difference between lists and array in Scala:
  • Lists are immutable whereas arrays are mutable in Scala.
  • Lists represents a linked list whereas arrays are flat.
Syntax:
val variable_name: List[type] = List(item1, item2, item3)
or
val variable_name = List(item1, item2, item3)
Some important points about list in Scala:
  • In a Scala list, each element must be of the same type.
  • The implementation of lists uses mutable state internally during construction.
  • In Scala, list is defined under scala.collection.immutable package.
  • A List has various methods to add, prepend, max, min, etc. to enhance the usage of list.
Example:
Output:
List 1:
List(Geeks, GFG, GeeksforGeeks, Geek123)

List 2:
C
C#
Java
Scala
PHP
Ruby
In above example simply we are printing two lists. Example:
Output:
The empty list is:
List()
Above example shows that the list is empty or not. Example:
Output:
The two dimensional list is:
List(List(1, 0, 0), List(0, 1, 0), List(0, 0, 1))
Basic Operations on Lists
The following are the three basic operations which can be performed on list in scala:
  1. head: The first element of a list returned by head method. Syntax:
    list.head //returns head of the list
    
    Example:
    Output:
    The head of the list is:
    C
    
  2. tail: This method returns a list consisting of all elements except the first. Syntax:
    list.tail //returns a list consisting of all elements except the first
    
    Example:
    Output:
    The tail of the list is:
    List(C#, Java, Scala, PHP, Ruby)
    
  3. isEmpty: This method returns true if the list is empty otherwise false. Syntax:
    list.isEmpty //returns true if the list is empty otherwise false.
    
    Example:
    Output:
    List is empty or not:
    false
    
How to create a uniform list in Scala
Uniform List can be created in Scala using List.fill() method. List.fill() method creates a list and fills it with zero or more copies of an element. Syntax:
List.fill() //used to create uniform list in Scala 
Example:
Output:
Programming Language : List(Scala, Scala, Scala)
number : List(4, 4, 4, 4, 4, 4, 4, 4)
Reversing List Order in Scala
The list order can be reversed in Scala using List.reverse method. List.reverse method can be used to reverse all elements of the list. Syntax:
list.reverse //used to reverse list in Scala 
Example:
Output:
Original list:List(1, 2, 3, 4, 5)
Reverse list:List(5, 4, 3, 2, 1)
Comment
Article Tags:
Article Tags:

Explore