### Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

## 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.

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.
}

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++) {
}

return result;
}``````

## 5. Conclusion

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

The example code from this article can be found over on GitHub.

### Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE