LoginSignup
1
0

More than 3 years have passed since last update.

ストリームAPI(Collectorsクラス)

Last updated at Posted at 2019-06-30

ストリームAPIとは

ストリームAPIは、コレクションや配列などのデータソースを元にして集計操作を行うAPIである。本記事では、終端操作のひとつであるCollectorsクラスについて記述する。Collectorsクラスは、Collectorインターフェースを実装している。collect()メソッドはストリームから要素をまとめて1つのオブジェクトを取得できる。

collect()メソッド

(1) <R,A> R collect(Collector<? super T,A,R> collector)
(2) <R> R collect(Supplier<R> supplier,BiConsumer<R ? superT> accumulator, BiConsumer<R,R> combiner)

Collectorsクラスのメソッド

(1) Collector<T,?,List<T>> toList()
(2) Collector<T,?,Integer> summingInt()
(3) Collector<T,?,Double> averagingInt()

Myclass.java
Stream<String> stream = Steam.of("aa","bb","cc");

//toListでストリームをリストにする
List<String> result1 = stream.collect(Collectors.toList());
System.out.print(result1); //[aa,bb,cc]

//summingIntはひとまとめにしたものの合計を出す
Integer result2 = stream.collect(Collectors.summingInt(x->x.length());
System.out.print(result2); //6

//averagingIntはストリームの平均値求める
Double result3 = stream.collect(Collectors.averagingInt(x->x.length()));
System.out.print(result2); //2.0

まとめ

Colectorsクラスに関しては「ひとまとめにして実行処理する」というイメージを持つ.

1
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
1
0