Learnitweb

Java Program to find the most repeated element in an array

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MostRepeatedElement {
    public static void main(String[] args) {
        int[] numbers = {1, 3, 2, 3, 4, 1, 3, 2, 2, 2}; // Example array

        int mostRepeated = Arrays.stream(numbers)
                .boxed() // Convert int to Integer
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) // Count occurrences
                .entrySet()
                .stream()
                .max(Map.Entry.comparingByValue()) // Find the max count
                .get()
                .getKey(); // Get the most frequent element

        System.out.println("Most Repeated Element: " + mostRepeated);
    }
}

Output:

Most Repeated Element: 2

Explanation:

  1. Convert int[] to Stream.boxed()
  2. Group elements and count occurrencesCollectors.groupingBy(Function.identity(), Collectors.counting())
  3. Find the maximum count.max(Map.Entry.comparingByValue())
  4. Get the key (most frequent element).get().getKey()

Alternative: Handling Multiple Max Elements

If multiple elements have the same highest frequency, return all:

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MostRepeatedElements {
    public static void main(String[] args) {
        int[] numbers = {1, 3, 2, 3, 4, 1, 3, 2, 2, 2};

        Map<Integer, Long> frequencyMap = Arrays.stream(numbers)
                .boxed()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        long maxCount = Collections.max(frequencyMap.values()); // Get max frequency

        List<Integer> mostRepeated = frequencyMap.entrySet().stream()
                .filter(entry -> entry.getValue() == maxCount)
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        System.out.println("Most Repeated Elements: " + mostRepeated);
    }
}

Output:

Most Repeated Elements: [2, 3]