import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<String> list = List.of("cat", "elephant", "ox");
list.stream()
.sorted(Comparator.comparingInt(String::length))
.forEach(System.out::println);
}
}
選択肢
- あなたの回答
- 正解
正解
B. ox cat elephant の順で表示
詳細解説
Comparator.comparingInt(String::length) は文字列長を昇順で比較します。ox(2)、cat(3)、elephant(8) の順に並んで表示されます。
なぜ他の選択肢が違うのか
- アルファベット順ではなく文字列長で並び替えられます。
- 降順ではなく昇順なので最長の elephant が最後になります。
- Comparator.comparingInt は正当なメソッドです。
罠ポイント
Comparator.comparingInt / comparingLong / comparingDouble を使うとプリミティブ型への変換を明示でき、ボクシングのコストを避けられます。