今回は「出現回数マップ」をさらに発展させて、出現回数ランキング(多い順に並べて表示) を作るサンプルを紹介します。
サンプルコード:出現回数ランキング
import java.util.*;
public class FrequencyRankingSample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Integer> numbers = new ArrayList<>();
System.out.println("整数をスペース区切りで入力してください(例: 10 20 30 20 10):");
String line = sc.nextLine();
// 入力を分割してリストに追加
String[] parts = line.split("\\s+");
for (String p : parts) {
try {
int n = Integer.parseInt(p);
numbers.add(n);
} catch (NumberFormatException e) {
System.out.println("数値に変換できません: " + p);
}
}
if (numbers.isEmpty()) {
System.out.println("有効な数値が入力されませんでした。");
return;
}
// 出現回数を数える Map
Map<Integer, Integer> countMap = new HashMap<>();
for (int n : numbers) {
countMap.put(n, countMap.getOrDefault(n, 0) + 1);
}
// Map をリストに変換してソート(出現回数の降順)
List<Map.Entry<Integer, Integer>> entryList = new ArrayList<>(countMap.entrySet());
entryList.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
// 結果表示
System.out.println("入力された整数リスト: " + numbers);
System.out.println("出現回数ランキング:");
int rank = 1;
for (Map.Entry<Integer, Integer> entry : entryList) {
System.out.println(rank + "位: " + entry.getKey() + "(" + entry.getValue() + "回)");
rank++;
}
}
}
Java✅ 実行例
整数をスペース区切りで入力してください(例: 10 20 30 20 10):
30 10 20 10 40 20 10 30
入力された整数リスト: [30, 10, 20, 10, 40, 20, 10, 30]
出現回数ランキング:
1位: 10(3回)
2位: 30(2回)
3位: 20(2回)
4位: 40(1回)
ポイント
- Map → List に変換してソートするのが定番テクニック
entryList.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));で「出現回数の降順」に並べ替え- 出現回数が同じ場合は入力順やキーの大小で順序が決まる(必要ならさらに条件を追加可能)
発展アイデア
- 出現回数が同じ場合に「値の昇順」で並べる
- 上位3位までだけ表示するランキングにする
- 出現回数をグラフ(テキスト棒グラフ)で可視化する
👉 ここまでで「入力 → 出現回数マップ → 最頻値 → 出現回数ランキング」まで完成しました。

