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?

More than 5 years have passed since last update.

Streamの終端処理

Posted at

Streamの生成処理およびStreamの中間処理
で処理をあたえたあとのStreamをどのような要素として終えるのか処理する

find系

検索および要素がのこっているかどうかの確認に使用

List<String> list = Arrays.asList("a","b","c","d","e");

// findFirst
String a = list.stream().filter(s -> s.equals("a")).findFirst().orElse(null);

// findAny
String any = list.stream().filter(s -> s.equals("a")).findAny().orElse(null);

match系

指定した条件式にあてはまるものがあるかどうかを判別する

List<String> list = Arrays.asList("alex","benjamin",null,"","elsa");

boolean nonNull = list.stream().allMatch(Objects::nonNull); //false

boolean isEmpty = list.stream().anyMatch(""::equals); //true

boolean isTom = list.stream().noneMatch("tom"::equals); //true

toArray

配列要素として処理したい場合に使用
toArray(引数なし)で処理するとObject[]になってしまうので注意

List<String> list = Arrays.asList("alex","benjamin","charley","dante","elsa");

Integer[] length = list.stream().map(String::length).toArray(Integer[]::new);

collect

ListなどのCollection要素として処理したい場合に使用
使いやすいのでよく使ってます(小並感)

List<String> list = Arrays.asList("alex","benjamin","charley","dante","elsa");

List<Integer> length = list.stream().map(String::length).collect(Collectors.toList());

count

生成処理、中間処理を終えたStream要素の数を集計する

List<String> list = Arrays.asList("alex","benjamin","charley","dante","elsa");

long count = list.stream().filter(s -> s.length() == 4 ).count(); // 2

forEach

Java8で追加された内部イテレータ
実はStreamにも使える。標準のforEachを使えばいいと思う()
下記のサンプルはどちらも同じ結果を得られます

一部ではStreamのforEachは禁忌として扱われているとか
(ほかの要素に変換するためのStreamなのに値を返さないから)

List<String> list = Arrays.asList("alex","benjamin","charley","dante","elsa");

// stream().forEach()
list.stream().filter(s -> s.length() == 4 ).forEach(System.out::println);

// list.forEach()
list.forEach(s -> {{if (s.length() == 4)System.out.println(s);}});

min,max

編集中

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?