5
4

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.

Java 8 新機能 Iterable#forEach

Posted at
  • このバージョンは正式リリース前です。

ループ式が追加されていた。

List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11, 12, 13);
intList.forEach(new Consumer<Integer>() {

	public void accept(Integer arg0) {
		// ここにループ処理
		System.out.println(arg0);
	}

	// default のため記述追加不要
	// public Consumer<Integer> chain(Consumer<? super Integer> arg0)
});

2種類以上の処理を続けるとき

List<Integer> intList = Arrays.asList(1, 3, 5, 7, 9, 11, 12, 13);
Consumer<Integer> consumer1 = new Consumer<Integer>() {

	public void accept(Integer arg0) {
		System.out.print("consumer1:");
		System.out.println(arg0);
	}
};
Consumer<Integer> consumer2 = new Consumer<Integer>() {

	public void accept(Integer arg0) {
		System.out.print("consumer2:");
		System.out.println(arg0 * 3);
	}
};
intList.forEach(consumer1.chain(consumer2));

実行結果

consumer1:1
consumer2:3
consumer1:3
consumer2:9
consumer1:5
consumer2:15
consumer1:7
consumer2:21
consumer1:9
consumer2:27
consumer1:11
consumer2:33
consumer1:12
consumer2:36
consumer1:13
consumer2:39

別クラスにすることによって長い処理を書き放題ってことかな。
これは

++ 65535 byte 制約回避のためですね

5
4
1

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
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?