Iteration through a Generic List (Java 5 version)

/ Published in: Java
Save to your folder(s)

This code uses the new Java 5 foreach loop to iterate through every element of a list. It avoids the need to declare an iterator.

Copy this code and paste it in your HTML
  1. List<String> listOfStrings = new LinkedList<String>( );
  3. listOfStrings.add("Why");
  4. listOfStrings.add("Iterate");
  5. listOfStrings.add("When");
  6. listOfStrings.add("You");
  7. listOfStrings.add("Can");
  8. listOfStrings.add("Avoid");
  9. listOfStrings.add("It!");
  11. for (String s: listOfStrings) {
  12. System.out.println(s);
  13. }

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.