Scala List distinct() operation with examples

 146 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about Scala List distinct() operation with examples.

List() is a collection to store values in an ordered fashion. distinct() operation is a useful operation Scala List which allows us to retrieve distinct/unique values from the list. When you call this operation on a Scala list, it returns a new collection with unique values, and duplicates will be discarded.

distinct() Syntax

def distinct: List[A]

Selects all the elements of this sequence ignoring the duplicates.

Scala List distinct() operation  example 1

object StaticReference {
  def main(args: Array[String]): Unit = {

    //create list
    var list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8)

    //Get distinct and print the result
    println(list.distinct)

  }
}

Output

List(1, 2, 3, 4, 5, 6, 7, 8)

Scala List distinct() operation  example 2

object Test {
  def main(args: Array[String]): Unit = {

    //create list
    var list: List[String] = List("red", "red", "red", "red")

    //Get distinct and print the result
    list.distinct.foreach(println)

  }
}

Output

red

ReferencesScala List distinct operation

I hope you like this tutorial and you were able to understand Scala list distinct operation with examples.

Thanks for reading and please give us a thumb up and comment below!

 

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.