I have a stream of elements and I want transform it to another stream that would consist only of elements that appeared the most in the previous stream assuming that I may have multiple elements with the same number of occurrences.
As an example:
Input stream: ['A', 'B', 'A', 'B', 'C', 'C', 'A', 'B']
Output stream: ['A', B'] as they both had max number of occurrences in the previous stream equal to 3.
So far I've written the following code:
stream.collect(toMap(w -> w, w -> 1, Integer::sum))
.entrySet()
.stream()
.max(comparing(Map.Entry::getValue))
.map(Map.Entry::getKey);
But this allows me to get only one of the elements with the max number of occurrences and for the case above it would give either 'A' or 'B'.
Is there any elegant way of how this can be achieved using lambdas?
Thanks, Cheers