How to Count Unique Numbers from a List of Integers in Java

The program below counts the unique number from a list of integers in Java:

import java.util.Arrays;
import java.util.Set;

public class CountUniqueNumbers {
	public int count(int[] numbers) {
        Set<Integer> distinctNums =;
		return distinctNums.size();

	public static void main(String[] args) {
		CountUniqueNumbers countUniqueNumbers = new CountUniqueNumbers();
		int count = countUniqueNumbers.count(new int[] { 1, 3, 4, 5, 5, 4 });


The above code gives the following output:


In the above example code, we have created a class named CountUniqueNumbers and imported the necessary packages for the program. The method is used to create a sequence stream from the specified int array. The boxed() method returns a Stream consisting of the elements and boxed to an integer. Next, collect() method is used to store the elements from the stream to a collection. The Collectors.toSet() method returns a Collector that creates a new Set from the input elements. Set removes duplicate elements and stores only unique elements. After removing the duplicate number the remaining numbers are counted by calling size() method. The size() method returns the size of elements in the list.