Count Repeated Elements in Array in Java

Counting repeated elements in a Java array involves identifying elements that appear more than once and tallying their occurrences. This can be achieved using nested loops, a HashMap, or other data structures for efficient tracking.

1. Count Repeated Elements in Array Using Nested Loops

This program example iterates through the array and compares each element with others to count repetitions, using a boolean array to avoid recounting visited elements.

package com.javacodepoint.array;

public class CountRepeatedElements {

	public static void main(String[] args) {
		int[] arr = { 10, 20, 20, 10, 30, 40, 10, 30 };
		boolean[] visited = new boolean[arr.length]; // To track visited elements

		System.out.println("Repeated elements and their counts:");
		for (int i = 0; i < arr.length; i++) {
			if (!visited[i]) {
				int count = 1;
				for (int j = i + 1; j < arr.length; j++) {
					if (arr[i] == arr[j]) {
						visited[j] = true;
						count++;
					}
				}
				if (count > 1) {
					System.out.println(arr[i] + ": " + count);
				}
			}
		}
	}
}

OUTPUT:
Repeated elements and their counts:
10: 3
20: 2
30: 2

2. Count Duplicate Elements in an Array Using HashMap Java

This program example uses a HashMap to store and efficiently count occurrences of each element, making it faster and more suitable for larger datasets.

package com.javacodepoint.array;

import java.util.HashMap;

public class CountRepeatedElements2 {
	
	public static void main(String[] args) {
		int[] arr = { 10, 20, 20, 10, 30, 40, 10, 30 };

		HashMap<Integer, Integer> elementCount = new HashMap<>();

		// Count occurrences
		for (int num : arr) {
			elementCount.put(num, elementCount.getOrDefault(num, 0) + 1);
		}

		System.out.println("Repeated elements and their counts:");
		for (int key : elementCount.keySet()) {
			if (elementCount.get(key) > 1) {
				System.out.println(key + ": " + elementCount.get(key));
			}
		}
	}
}

OUTPUT:
Repeated elements and their counts:
20: 2
10: 3
30: 2

Notes:

  • Example-1: Simple but less efficient for larger arrays due to O(n^2) time complexity.
  • Example-2: More efficient with O(n) time complexity and easier to implement for counting occurrences.

Read Also: Remove duplicate elements in an Array. | Find the Largest Number in an Array.

Java logical programs list


Java Basic Programs

Java String Programs

Java Miscellaneous Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *