Scala program to print the distinct elements of the array

Here, we are going to learn how to print the distinct elements of the array in Scala programming language?
Submitted by Nidhi, on May 25, 2021 [Last updated : March 10, 2023]

Scala – Printing Distinct Elements of an Array

Here, we will create an array of integer elements. Then we will use the distinct() method to get the distinct elements of the array. The distinct() method returns an array that contains distinct elements.

Scala code to print the distinct elements of an array

The source code to print the distinct elements of the array is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to print the
// distinct elements of the array

object Sample {

  def main(args: Array[String]) {
    var arr1 = Array(10, 23, 14, 16, 10, 14, 13, 60);

    var i: Int = 0;

    var arr2 = arr1.distinct;

    i = 0;
    println("Distinct elements of array: ")
    while (i < arr2.length) {
      printf("%d ", arr2(i));
      i = i + 1;
    }
    println();
  }
}

Output

Distinct elements of array: 
10 23 14 16 13 60

Explanation

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

In the main() function, we created an array arr1 that contains integer elements. Then we used the distinct() method to get the distinct elements of array arr1 and assigned the result into arr2. After that, we printed the elements of array arr2 on the console screen.

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.