Java Online Compiler
Example: CountDistinctElementsUsingStreamAPI in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// CountDistinctElementsUsingStreamAPI import java.util.Arrays; public class Main { public static void main(String[] args) { // Step 1: Define the input array int[] arr = {10, 20, 10, 30, 40, 20, 50}; // Step 2: Convert the array to an IntStream // Step 3: Apply the distinct() operation to get unique elements // Step 4: Use count() to get the total number of distinct elements long distinctCount = Arrays.stream(arr) // Creates an IntStream from the array .distinct() // Returns a stream with unique elements .count(); // Counts the elements in the distinct stream // Step 5: Print the result System.out.println("Original Array: " + Arrays.toString(arr)); System.out.println("Number of distinct elements (Stream API): " + distinctCount); } }
Output
Clear
ADVERTISEMENTS