Assume a list:
List<String> items = Arrays.asList("apple", "banana", "apple", "orange", "banana", "apple");
Using Collectors.groupingBy + max()
String mostFrequent = items.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null); // returns null if list is empty
System.out.println(mostFrequent);
Output:
apple
Summary:
Collectors.groupingBy(..., Collectors.counting())counts occurrences of each element..max(Map.Entry.comparingByValue())finds the entry with the highest count..map(Map.Entry::getKey)extracts the most frequent element.- Returns
nullif the list is empty.
