Counting Unique Numbers in a List of Integers

  • Last updated Apr 25, 2024

In this Java programming tutorial, learn how to efficiently count the number of unique integers in a given list.

Here's an example Java code snippet that demonstrates how to count the number of unique integers in a given list:

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class Example {

   public static void main(String[] args) {

      int[] numbers = new int[] { 1, 3, 4, 5, 5, 4, 8, 9, 6, 9, 4 };
      Set<Integer> uniqueNums = Arrays.stream(numbers).boxed().collect(Collectors.toSet());
      int count = uniqueNums.size();
      System.out.println(count);

   }

}

The output of the above code is as follows:

7

In this example, the code defines an array called numbers containing duplicate integers. The Arrays.stream(numbers) method converts the array into a stream of integers. The boxed() method is used to convert the stream of primitive integers to a stream of boxed Integer objects. The collect(Collectors.toSet()) operation collects the stream elements into a Set data structure. As a Set only allows unique values, it effectively removes any duplicate numbers from the array. The uniqueNums variable holds the resulting set of unique numbers. The uniqueNums.size() method retrieves the count of distinct elements in the uniqueNums set. Finally, the count variable holds the count of unique numbers, and it is printed to the console using System.out.println().