5
5

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 [改定]

Last updated at Posted at 2014-03-20

旧記事:http://qiita.com/asahina_dev/items/44a5325b0192b729cd4c

正式リリースされてメソッド名がかわっていたので改定してみた。
ついでに lamuda で記述。

初期化
List<Integer> list =Arrays.asList(1,2,3,4,5,6,7,8,9,10,11);

通常

list.forEach(a -> { System.out.printf("consumer1: %5d %n", a);});

二種類

だめな例なんだろうな

list.forEach(
  ((Consumer<Integer>) a -> { System.out.printf("consumer2: %5d %n", a);})
  .andThen(            a -> { System.out.printf("consumer3: %5d %n", a * 3);}));

やるならこうだろうね。

Consumer<Integer> consumer4 = a->System.out.printf("consumer4: %5d %n", a);
Consumer<Integer> consumer5 = a->System.out.printf("consumer5: %5d %n", a*4);
list.forEach(consumer4.andThen(consumer5));

実行結果

consumer1:     1 
consumer1:     2 
consumer1:     3 
consumer1:     4 
consumer1:     5 
consumer1:     6 
consumer1:     7 
consumer1:     8 
consumer1:     9 
consumer1:    10 
consumer1:    11 

consumer2:     1 
consumer3:     3 
consumer2:     2 
consumer3:     6 
consumer2:     3 
consumer3:     9 
consumer2:     4 
consumer3:    12 
consumer2:     5 
consumer3:    15 
consumer2:     6 
consumer3:    18 
consumer2:     7 
consumer3:    21 
consumer2:     8 
consumer3:    24 
consumer2:     9 
consumer3:    27 
consumer2:    10 
consumer3:    30 
consumer2:    11 
consumer3:    33 

consumer4:     1 
consumer5:     4 
consumer4:     2 
consumer5:     8 
consumer4:     3 
consumer5:    12 
consumer4:     4 
consumer5:    16 
consumer4:     5 
consumer5:    20 
consumer4:     6 
consumer5:    24 
consumer4:     7 
consumer5:    28 
consumer4:     8 
consumer5:    32 
consumer4:     9 
consumer5:    36 
consumer4:    10 
consumer5:    40 
consumer4:    11 
consumer5:    44 
5
5
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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?