![](/img/trans.png)
[英]How to find the most frequently occurring character in a string with Java?
[英]How to display the most frequently occurring letter and the number of matches using streams?
我有一個方法可以創建一個隨機英文字母列表並計算每個字母在列表中出現的次數。 如何只顯示最常出現的字母以及這個字母在這個列表中出現了多少次?
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));
}
}
最簡單的解決方案是使用groupingBy
並將每個字母的計數存儲在 map 中。然后只需 stream 條目集並使用 max 來獲取編號最高的條目。
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));
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.