Scala Collections – List (sort, foreach)

Category : Scala | Sub Category : Scala Programs | By Runner Dev Last updated: 2020-10-08 19:09:02 Viewed : 226


Scala Collections – List (sort, foreach) 

·        override def apply[A](xs: A*): List[A]

 Creates a collection with the specified elements. 

·        final override def foreach[U](f: Int => U): Unit

Applies a function f to all elements of this list.

Note: this method underlies the implementation of most other bulk operations. Subclasses should re-implement this method if a more efficient implementation exists. 

·     def sorted[B >: Int](implicit ord: Ordering[B]): List[Int]

Sorts this list according to an Ordering.

The sort is stable. That is, elements that are equal (as determined by lt) appear in the same order in the sorted sequence as in the original. 

·        override def reverse: List[Int]

Returns new list with elements in reversed order. 

 Example:

Following example illustrates about Scala List-sort,foreach and merge

Save the file as −  ListExampleApp1.scala 

ListExampleApp1.scala

 package runnerdev 

object ListExampleApp1 extends App{ 

  //Applying predefined methods

  var list = List(125691012134)

  var list2 = List(100200)

  print("Elements: ") 

  // Iterating using foreach loop

 list.foreach((element: Int) => print(element + " ")) 

// Accessing element of 2 index

 print(" Element at 2 index: " + list(2))

  // Merging two list 

  var list3 = list ++ list2

  print(" Elements after merging list and list2: ")

  list3.foreach((element: Int) => print(element + " ")) 

  var list4 = list3.sorted // Sorting list

  print(" Elements after sorting list3: ")

  list4.foreach((element: Int) => print(element + " ")) 

  var list5 = list3.reverse // Reversing list elements

  print(" Elementss in reverse order of list5: ")

  list5.foreach((element: Int) => print(element + " "))

}

 

 

compile and run the above example as follows 

scala> scalac ListExampleApp1.scala

scala> scala ListExampleApp1 

Output:

Elements: 1 2 5 6 9 10 12 13 4

Element at 2 index: 5

Elements after merging list and list2: 1 2 5 6 9 10 12 13 4 100 200

Elements after sorting list3: 1 2 4 5 6 9 10 12 13 100 200

Elementss in reverse order of list5: 200 100 4 13 12 10 9 6 5 2 1

Search
Sub-Categories
Related Articles

Leave a Comment: