Skip to content

Instantly share code, notes, and snippets.

@teachingprogramming
Created May 8, 2018 02:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teachingprogramming/bb8eccce1821d878fd1b60f3a872a68f to your computer and use it in GitHub Desktop.
Save teachingprogramming/bb8eccce1821d878fd1b60f3a872a68f to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
public class ListSample {
public static void main(String[] args) {
// 文字列のリストを作成(インスタンス化)
List<String> stringList = new ArrayList<String>();
// 文字列をリストに追加する
stringList.add("文字列1");
stringList.add("文字列2");
stringList.add("文字列3");
stringList.add("文字列4");
// 個数を調べる
int x = stringList.size();
System.out.println("stringListに入っている文字列の個数は" + x + "個です。");
// インデックスを指定して取得する
int index = 2;
String str = stringList.get(index);
System.out.println("stringListの" + index + "番目に入っている文字列は" + str + "です。");
// 全て取得、表示する (1) 普通のfor
for (int i = 0; i < stringList.size(); i++) {
System.out.println(stringList.get(i));
}
// 全て取得、表示する (2) 拡張for
for (String s : stringList) {
System.out.println(s);
}
// 全て取得、表示する (3) forEachメソッド + ラムダ式
stringList.forEach(s -> System.out.println(s));
// 全て取得、表示する (4) forEachメソッド + メソッド参照
stringList.forEach(System.out::println);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment