Last active
August 29, 2015 14:08
-
-
Save KazukoShikiya/fcbffb51cf1e3edee60f to your computer and use it in GitHub Desktop.
配列要素を先頭から処理することについての進化
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Java5前には、配列先頭から要素を取り出す…は、こんな感じでした | |
public class BeforJava5{ | |
public static void main(String[] args) { | |
List texts = new ArrayList(); | |
texts.add("Hello"); | |
texts.add("Good bye"); | |
// Iterator(イテレータ)を使って、要素の先頭から末尾へと要素取り出しをする | |
Iterator ite = texts.iterator(); | |
while(ite.hasNext()){ //まだ要素があるかチェック | |
String text = (String)ite.next(); // 要素取り出し | |
System.out.println(text); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AfterJava5{ | |
public static void main(String[] args) { | |
List<String> texts = new ArrayList<>(); | |
texts.add("Hello"); | |
texts.add("Good bye"); | |
/* | |
Iterator(イテレータ)は使わず、拡張for文で記述する | |
拡張for文は、配列要素の先頭から1つづつ要素を取り出してくれる | |
*/ | |
for(String text : texts){ | |
System.out.println(text); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Java SE 8では、配列要素に対してのアプローチが変わった(従来の方法でも書けるが…) | |
public class Java8Later{ | |
public static void main(String[] args) { | |
List<String> texts = new ArrayList<>(); | |
texts.add("Hello"); | |
texts.add("Good bye"); | |
/* | |
拡張for文は使わず、関数操作で記述する | |
.stream()は、ストリームオブジェクトに変換する | |
.foreach()は、ストリームの各要素1つ1つに対して{}内の処理を実行する | |
*/ | |
texts.stream().forEach((text) -> { | |
System.out.println(text); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment