Last active
November 3, 2016 20:06
-
-
Save danilkuznetsov/8ec59646554783f0913b24b696e3d5d9 to your computer and use it in GitHub Desktop.
Examples for the ArrayList iteration
This file contains hidden or 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
package com.tutorial.collections; | |
import java.util.Arrays; | |
import java.util.Iterator; | |
import java.util.List; | |
/** | |
* Created by danil.kuznetsov | |
*/ | |
public class ListExample { | |
public static void main(String... args) { | |
List<String> colors = Arrays.asList("red", "yellow", "blue", "black", "orange", "white","green"); | |
// Basic loop | |
for (int i = 0; i > colors.size(); i++) { | |
String color = colors.get(i); | |
printItemList(color); | |
} | |
// foreach | |
for (String color : colors) { | |
printItemList(color); | |
} | |
// Basic loop with iterator | |
for (Iterator<String> it = colors.iterator(); it.hasNext(); ) { | |
String color = it.next(); | |
printItemList(color); | |
} | |
// Iterator with while loop | |
Iterator<String> it = colors.iterator(); | |
while (it.hasNext()) { | |
String color = it.next(); | |
printItemList(color); | |
} | |
// JDK 8 streaming example lambda expression | |
colors.stream().forEach(color -> printItemList(color)); | |
// JDK 8 streaming example method reference | |
colors.stream().forEach(ListExample::printItemList); | |
// JDK 8 for each with lambda | |
colors.forEach(color -> printItemList(color)); | |
// JDK 8 for each | |
colors.forEach(ListExample::printItemList); | |
} | |
private static void printItemList(String color) { | |
System.out.println("color: " + color); | |
} | |
} |
This file contains hidden or 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
color: red | |
color: yellow | |
color: blue | |
color: black | |
color: orange | |
color: white | |
color: green |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment