Close

Java Collections - How to find distinct elements count in collections and arrays?

[Updated: Apr 17, 2020, Created: Apr 10, 2020]

Java Collections Java 

Following examples shows how to find distinct element count in collections and arrays:

package com.logicbig.example;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.IntStream;

public class DistinctElementCountExample {
  public static void main(String[] args) {
      //list example
      List<Integer> intList = Arrays.asList(1, 4, 3, 2, 6, 4, 3, 2, 1);
      long distinctCount = new HashSet<>(intList).size();
      System.out.println(distinctCount);
      //list example using java 8 stream
      distinctCount = intList.stream().distinct().count();
      System.out.println(distinctCount);

      //Array example
      Integer[] intArray = {1, 4, 3, 2, 6, 4, 3, 2, 1};
      long distinctCount2 = new HashSet<>(Arrays.asList(intArray)).size();
      System.out.println(distinctCount2);
      //Array using java 8 stream
      distinctCount2 = Arrays.stream(intArray).distinct().count();
      System.out.println(distinctCount2);

      //Array of primitives using java 8 stream
      int[] intArray2 = {1, 4, 3, 2, 6, 4, 3, 2, 1};
      long distinctCount3 = IntStream.of(intArray2).distinct().count();
      System.out.println(distinctCount3);
  }
}
5
5
5
5
5

See Also