Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this short tutorial, we’ll see how to find the n most frequent elements in a Java array.

2. Using HashMap and PriorityQueue

We can use a HashMap to count the occurrences of each element and a PriorityQueue to prioritize elements based on their count.

This allows us to find the n most frequent elements in the array efficiently:

public static List<Integer> findByHashMapAndPriorityQueue(Integer[] array, int n) {
    Map<Integer, Integer> countMap = new HashMap<>();

    // For each element i in the array, add it to the countMap and increment its count
    for (Integer i : array) {
        countMap.put(i, countMap.getOrDefault(i, 0) + 1);
    }

    // Create a max heap (priority queue) that will prioritize elements with higher counts.
    PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> countMap.get(b) - countMap.get(a));

    // Add all the unique elements in the array to the heap.
    heap.addAll(countMap.keySet());

    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < n && !heap.isEmpty(); i++) {
        // Poll the highest-count element from the heap and add it to the result list.
        result.add(heap.poll());
    }

    return result;
}

Let’s test our methods:

Integer[] inputArray = {1, 2, 3, 2, 2, 1, 4, 5, 6, 1, 2, 3};
Integer[] outputArray = {2, 1, 3};
assertThat(findByHashMapAndPriorityQueue(inputArray, 3)).containsExactly(outputArray);

3. Using the Stream API

We can also use the Stream API to create a Map to count the occurrences of each element, sort the entries in the map by frequency in descending order, and then extract the n most frequent elements:

public static List<Integer> findByStream(Integer[] arr, int n) {
    return Arrays.stream(arr).collect(Collectors.groupingBy(i -> i, Collectors.counting()))
      .entrySet().stream()
      .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
      .map(Map.Entry::getKey)
      .limit(n)
      .collect(Collectors.toList());
}

4. Using TreeMap

Alternatively, we can use a TreeMap and create a custom Comparator that compares the values in the Map.Entry objects in the map by frequency in descending order:

public static List<Integer> findByTreeMap(Integer[] arr, int n) {
    // Create a TreeMap and use a reverse order comparator to sort the entries by frequency in descending order
    Map<Integer, Integer> countMap = new TreeMap<>(Collections.reverseOrder());

    for (int i : arr) {
        countMap.put(i, countMap.getOrDefault(i, 0) + 1);
    }

    // Create a list of the map entries and sort them by value (i.e. by frequency) in descending order
    List<Map.Entry<Integer, Integer>> sortedEntries = new ArrayList<>(countMap.entrySet());
    sortedEntries.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));

    // Extract the n most frequent elements from the sorted list of entries
    List<Integer> result = new ArrayList<>();
    for (int i = 0; i < n && i < sortedEntries.size(); i++) {
        result.add(sortedEntries.get(i).getKey());
    }

    return result;
}

5. Conclusion

In summary, we’ve learned different ways to find the n most frequent elements in a Java array.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

2 Comments
Oldest
Newest