Skip to content

Instantly share code, notes, and snippets.

@danilkuznetsov
Last active November 3, 2016 20:06
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 danilkuznetsov/8ec59646554783f0913b24b696e3d5d9 to your computer and use it in GitHub Desktop.
Save danilkuznetsov/8ec59646554783f0913b24b696e3d5d9 to your computer and use it in GitHub Desktop.
Examples for the ArrayList iteration
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);
}
}
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