Home > front end >  How to display the most frequently occurring letter and the number of matches using streams?
How to display the most frequently occurring letter and the number of matches using streams?

Time:02-08

I have a method that creates a list of random English letters and counts how many times each letter appears in the list. How to display only the letter that occurs most often and how many times does this letter occur in this list?

public class StreamPractice {

    public static void main(String[] args) {
        System.out.println(mostFrequentlyOccurringLetter());
    }

    private static Map<String, Integer> mostFrequentlyOccurringLetter() {
        return new Random().ints(100, 65, 91)
                .mapToObj(i -> String.valueOf((char) i))
                .collect(Collectors.toMap(Function.identity(), value -> 1, Integer::sum));
    }

}

CodePudding user response:

The easiest solution is to use groupingBy and store the count of each letter in a map. Then just stream the entry set and use max to get the entry with the highest number.

Map<String, Long> occurrences = new Random().ints(100, 65, 91)
    .mapToObj(i -> String.valueOf((char) i))
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting());   
Optional<Map.Entry<String, Long>> max = occurrences.entrySet()
    .stream()
    .max(Comparator.comparing(Map.Entry::getValue));

CodePudding user response:

Map<String, Integer> map = new Random().ints(100, 65, 91)
        .mapToObj(i -> String.valueOf((char) i))
        .collect(Collectors.toMap(Function.identity(), value -> 1, Integer::sum));
map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByValue().reversed()) 
        .findFirst();
  •  Tags:  
  • Related