Answer the question
In order to leave comments, you need to log in
How to find elements in List having more occurrences in Java?
There is a list of strings:
List<String> s = Arrays.asList("a", "a", "a", "b", "c");
// получим количество повторений по каждой букве (a = 3, b = 1, c = 1)
Map<String, Long> map= s.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// Из этого списка уже получаем букву с самым большим количеством повторений (это буква "а")
Optional<String> mostCommon = map.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey);
// a = 3 и b = 3
List<String> s = Arrays.asList("a", "a", "a", "b", "b", "b", "b", "c");
Set<Srring> mostWidelyUsed = map.entrySet().stream()
.map(v -> Collections.max(v, Map.Entry.comparingByValue()))
.collect(Collectors.toSet());
Answer the question
In order to leave comments, you need to log in
var s = Arrays.asList("a", "a", "a", "b", "b", "b", "c");
var map = s.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
var max = map.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getValue)
.orElse(0L);
var result = map.entrySet().stream()
.filter(e -> e.getValue().equals(max))
.map(Map.Entry::getKey)
.collect(Collectors.toList()); // [a, b]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question