Java program to print unique values from a list

JavaObject Oriented ProgrammingProgramming

To print unique values from a List in Java, the code is as follows −

Example

 Live Demo

import java.io.*;
public class Demo{
   static void distinct_vals(int my_arr[], int len){
      for (int i = 0; i < len; i++){
         int j;
         for (j = 0; j < i; j++)
         if (my_arr[i] == my_arr[j])
            break;
         if (i == j)
         System.out.print( my_arr[i] + " ");
      }
   }
   public static void main (String[] args){
      int my_arr[] = {55, 67, 99, 11, 54, 55, 88, 99, 1, 13, 45};
      int arr_len = my_arr.length;
      System.out.println("The distinct elements in the array are ");
      distinct_vals(my_arr, arr_len);
   }
}

Output

The distinct elements in the array are
55 67 99 11 54 88 1 13 45

A class named Demo contains a function named ‘distinct_vals’ that takes in the array and the length of the array as parameters. It iterates over the array and checks for duplicate values and prints only the unique values of the array. In the main function, an array is defined and its length is stored in a variable. This ‘distinct_vals’ function is called with the defined array and length and the result is displayed on the console.

raja
Published on 07-Jul-2020 13:17:39
Advertisements