LoginSignup
11
10

More than 5 years have passed since last update.

Streamでcollect(Collectors.toList())は絶対にnullにならない件

Posted at

collect(Collectors.toList())を使用した場合、戻り値のnullチェックが必要かどうか調べました。

可変リダクション操作(mutable reduction operation)とは

リダクション操作とは、一連の要素に特定の演算を適用して1つにまとめる操作です。
Stream#collectでは、Listのような可変なオブジェクトに要素を収集するため、「可変リダクション操作」と呼んでいるようです。

Collector

Collectorインターフェースでは4つのメソッドを定義しており、4つのメソッドの戻り値は全て関数オブジェクトになっています。

メソッド 工程
supplier 前処理
accumulator 集積
combiner 結合
finisher 後処理

Collector.toList()

toList()のソースを見てみると、前処理はArrayListをnewしているため、
空リストが必ず生成されて、戻り値はnullにはならないことをわかりました。

Collectors.java
public static <T>
Collector<T, ?, List<T>> toList() {
    return new CollectorImpl<>((Supplier<List<T>>) ArrayList::new, List::add,
                               (left, right) -> { left.addAll(right); return left; },
                               CH_ID);
}

ということで、null checkは不要、empty checkだけで十分です。

11
10
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
11
10