Posted By

cpjobling on 03/01/07


Tagged

list iterator foreach


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

zdroshnya


Iteration through a Generic List (Java 5 version)


 / Published in: Java
 

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.

  1. List<String> listOfStrings = new LinkedList<String>( );
  2.  
  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!");
  10.  
  11. for (String s: listOfStrings) {
  12. System.out.println(s);
  13. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: stel on February 14, 2018

can I use this code to iterate a two dimensional list and sort it alphabetically? And will it work on Java 8? Guess once done with working on this web site will try it myself but thought would ask you. Maybe you have some other interesting ideas on how I can do it.

You need to login to post a comment.