J
J
Jake Taylor2021-11-08 16:30:53
Java
Jake Taylor, 2021-11-08 16:30:53

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");

To find the most frequently occurring letter using stririm:
// получим количество повторений по каждой букве (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);


And how to get several letters, which will have the same maximum number of repetitions :
// a = 3 и b = 3
List<String> s = Arrays.asList("a", "a", "a", "b", "b", "b", "b", "c");


Tried something like this, but it doesn't work:
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

1 answer(s)
D
Dmitry Roo, 2021-11-08
@n199a

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 question

Ask a Question

731 491 924 answers to any question