0
2

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

Last updated at Posted at 2018-07-01

#目的
streamでざっくりどんなことができるか知る。
とりあえず見てビビらない。なんとなくかけるようにする。

#コード
##基本形

		// 例えばこんなリストを作る
		List<String> list = new ArrayList<String>();
		list.add("sample");
		list.add("sample1");
		list.add("sample2");
		list.add("sample3");
		list.add("sample4");
		list.add("sample5");

		list
		.stream() // 対象のcollectionの加工開始
		.filter(s -> s.length() == 6) // 中間操作(加工)
		.forEach(s -> System.out.println(s)); // 終端操作(最後の処理)
		
		 // sampleのみ出力

このようにcollectionのstream()メソッドを使い、いくつかの中間操作を行い最後に終端操作を行うことで形にする。

##基本だけど
stream()はListで使われているけど、ListにメソッドがあるだけでインターフェイスとしてStreamは存在する。だから

Stream<String> st = list.stream();
st.forEach(s -> System.out.println(s));

のようなこともできる。

##終端操作
###forEach
voidなメソッドなので注意

list.stream().forEach(s -> sampleClass.stringList.add(s));
sampleClass.stringList.stream().forEach(s -> System.out.println(s));

###collect
stream()でいじってもListは返してくれないのでcollect()を使う

List<String>editList = list.stream().filter(s -> s.length() == 6).collect(Collectors.toList());
		editList.stream().forEach(s -> System.out.println(s));

他にも要素数を返すcount()など操作あり

##中間操作を使う
後は種々の中間操作を入れ込むだけ
使用頻度が高そうなものを記載

		.stream()
		.distinct() // 重複削除
		.filter(s -> !s.isEmpty()) // isEmpty()でないものみ残す
		.sorted() // 単純に昇順
		.sorted(Comparator.reverseOrder()) // 単純に降順
		.map(changeToLength) // 作成したFunctionを使用する
		.forEach(s -> System.out.println(s));

なお作成したFunctionは以下

		// Stringを引数、Integerを戻り値としてchangeToLengthというFunctionを作成
		// String s に対して{}内の処理を行う。
		Function<String, Integer> changeToLength= (String s) -> {
			return s.length();
		};
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?