第6章 並行処理の機能強化 : 問題 7 : ConcurrentHashMap の reduce メソッド
問題
ConcurrentHashMap<String, Long>
内で、最大値を持つキーを見つけよ
同じ Long 値であれば、どのキーであっても構わない
準備
戦争と平和の単語(57万5343語)の出現回数のマップを使う
ただし、3文字以下の単語は切り捨てる(でないと the が圧倒的だもんね)
■ 単語一覧の取得
List<String> words; String contents = new String( Files.readAllBytes(Paths.get("war-and-peace.txt")), StandardCharsets.UTF_8 ); words = Arrays.asList(contents.split("[\\P{L}]+"));
■ 単語の出現回数
ConcurrentHashMap<String, Long> map; map = (ConcurrentHashMap<String, Long>)words.stream() // キャストがちょっと不安だが… .filter(w -> w.length() >= 4) .map(String::toLowerCase) .collect( Collectors.toConcurrentMap( // 戻り値の実際の型は ConcurrentHashMap Function.identity(), w -> 1L, Long::sum ) );
解答
Map.Entry<String, Long> maxCount = map.reduceEntries( 1, (e1, e2) -> e1.getValue() > e2.getValue() ? e1: e2 ); System.out.println("最も多く出現した単語は " + maxCount.getKey());
ちなみに、最も多く出現した単語は that で 8204 回です