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.

Posted By: sxcaskjc on May 3, 2018

ShowBox Latest
VidMate Latest
Mobdro Latest Thanks for sharing.I found a lot of interesting information here. A really good post, very thankful and hopeful that you will write many more posts like this one.

Posted By: Mary476 on June 26, 2018

The 4 Methods for Iterating Collections in Java: Mobdro

  1. The Classic For Loop
  2. The Iterator Method
  3. The Enhanced For Loop
  4. The forEach Method with Lambda Expressions
Posted By: peerji on August 13, 2018

Awesome. WPSWPATester APKDODO CARTOONHD

You need to login to post a comment.