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

for / forEach / 拡張for

Last updated at Posted at 2023-12-13

for / forEach / 拡張for 書き方の違い

ArrayListの要素を一つずつ出力するプログラムを
for / forEach / 拡張for文でそれぞれ記載します。

ArrayList中身

ArrayList<String> fruitList = new ArrayList<>();
fruitList.add("Apple");
fruitList.add("Orange");
fruitList.add("Banana");

for文

for文
for(Integer i = 0; i < fruitList.size(); i++){
    System.out.println(fruitList.get(i));
}
/*[Apple, Orange, Banana]*/

forEach文

java8以降で使用可能

ちなみに -> は アロー と呼ぶらしい。

forEach(省略版)
fruitList.forEach((String fruitName) -> {
    System.out.println(fruitName);
});

forEach文(省略版)

java8以降で使用可能
※引数のデータ型は省略できる。
※引数が一つの時、引数を記載している()も省略できる。
※処理が一つの時、処理を記載している{}と処理の最後の;も省略できる。

forEach(省略版)
fruitList.forEach(fruitName -> System.out.println(fruitName));
/*[Apple, Orange, Banana]*/

拡張for文

java5以降で使用可能

拡張for文
for (String fruitName : fruitList){
    System.out.println(fruitName);
}
/*[Apple, Orange, Banana]*/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?