diff --git a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java index ea127ea587..0d78691bcc 100644 --- a/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java +++ b/algorithms-modules/algorithms-miscellaneous-7/src/main/java/com/baeldung/algorithms/frequentelements/MostFrequentElementsFinder.java @@ -30,22 +30,12 @@ public class MostFrequentElementsFinder { } public static List findByStream(Integer[] arr, int n) { - // Create a Map to count occurrences of each element - Map countMap = Arrays.stream(arr) - .collect(Collectors.groupingBy(i -> i, Collectors.counting())); - - // Sort the elements by occurrence count - List sortedKeys = countMap.entrySet().stream() + 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()); - - // Extract the n most frequent elements from the sorted list - List result = new ArrayList<>(); - for (int i = 0; i < n && i < sortedKeys.size(); i++) { - result.add(sortedKeys.get(i)); - } - return result; } public static List findByTreeMap(Integer[] arr, int n) {