Monday 16 May 2022

Scala Function - distinct and distinctBy

 Distinct - It creates a copy of a given collection without duplicated elements

DistinctBy - It also creates a copy given collection by keeping only one of the elements that produce the same key after applying the given anonymous function.

In below example:

if we apply isGreaterThan2 function to List(5,4,3,33,2,1,1), the keys will be generated as (true, true, true,true,false,false,false)

Thus it will only keep first element "5" which true and another element "2" which is false and rest will be ignored.


def distinctExample(): Unit = {
    val input1 = List(5,4,3,33,2,1,1)
    val distinctInput1 = input1.distinct
    println(s"distinctInput1 = $distinctInput1") // List(5, 4, 3, 33, 2, 1)

    val multiplyBy2 = ( num: Int ) => num * 2
    val distinctByInput1 = input1.distinctBy(multiplyBy2)
    println(s"distinctByInput1 = $distinctByInput1") // List(5, 4, 3, 33, 2, 1)

    val isGreaterThan2 = ( num: Int ) => num > 2
    val distinctByInput1ForGreaterThan2 = input1.distinctBy(isGreaterThan2)
    println(s"distinctByInput1ForGreaterThan2 = $distinctByInput1ForGreaterThan2") //List(5, 2)

  }