0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Collectors.groupingByの戻り値を TreeMapやLinkedHashMapにしたい

Posted at

Collectors.groupingBy の戻り値を TreeMapLinkedHashMapにしたい場合は、第2引数にMapの生成方法を指定します。

例 : リスト内の単語を頭文字ごとに数えた結果をTreeMapに格納する。

List<String> words = List.of("Cake", "Bird", "Apple", "Car", "Book", "Cat");
TreeMap<Character, Long> treemap = words.stream().collect(Collectors.groupingBy(word -> word.charAt(0), TreeMap::new, Collectors.counting()));
System.out.println(treemap); // => {A=1, B=2, C=3}

LinkedHashMap にしたい場合は LinkedHashMap::new と指定するだけです。

環境情報

  • javac 21.0.6
  • openjdk 21.0.6 2025-01-21 LTS
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?