3 Ways to Traverse a List

There are primarily 3 ways I can think of to traverse a java.util.List:

  • Using a traditional for loop;
  • Using a simplified for loop, or "foreach" statement in JDK 5 ;
  • Using java.util.Iterator
 public static void traverse(List data) {
System.out.println("Using simplified for loop/foreach:");
for(Object obj : data) {

System.out.println("Using for loop:");
for(int i = 0, n = data.size(); i < n; i++) {

System.out.println("Using Iterator:");
for(Iterator it = data.iterator(); it.hasNext();) {
I always use the for loop and JDK 5 enhanced for loop, and avoid using Iterator to traverse List. If you see other ways, feel free to add them in comment section.

Is there a foreach statement in JDK 1.5? Yes, but the word foreach is not a keyword in java, and I doubt it will ever be. Java foreach statement uses a simplified, or enhanced for loop (see examples above). Therefore, JDK 1.5 doesn't need to introduce new keywords like foreach, forEach, or for each, and foreach/forEach can continue to be used as valid identifier/variable names.


Anonymous said...

Avoiding using the Iterator? You *must* be kidding. Try traversing the LinkedList with 100000 entries using get(i) and see where it gets you with O(N*N) instead of O(N).

Anonymous said...

I'd love to know why the previous commenter would want to use a LinkedList at all. It is almost always better to use ArrayList (do some performance tests, and also consider memory usage...)

howto said...

To be honest, I didn't have LinkedList in mind at the time of writing this blog. I guess it's not common to use a sequential LinkedList. In fact, I haven't used it since I came out of school.

Yes, for LinkedList, using Iterator has better performance, esp for a large list.

The LinkedList javadoc says: "Operations that index into the list will traverse the list from the begining or the end, whichever is closer to the specified index."

Its superclass AbstractSequentialList javadoc says: "This class is the opposite of the AbstractList class in the sense that it implements the "random access" methods (get(int index), set(int index, Object element), set(int index, Object element), add(int index, Object element) and remove(int index)) on top of the list's list iterator, instead of the other way around."

Anonymous said...

Stephen, let's put it this way. We all know to "program to the interface". So, if you write an API that gets a List, then you should expect dealing efficiently with any List implementation, including LinkedList. So, it's not the question of when do *you* use the LinkedList. As the API writer, you can not force the implementation on the users. And believe me, there are good examples of using LinkedList. ArrayList just looks like the golden hammer to those that came from C's arrays.

javin paul said...

Nice article. There is another similar question usually asked in interview is four way of getting elements from hashMap which I have included here <a href="http://javarevisited.blogspot.com/2011/04/top-20-core-java-interview-questions.html>Top 20 Core Java Interview question</a>


Aashish said...

You can find out the cycle or loop in a single linked list by using two pointer approach.
Below link can be useful to find out the algorithm to find cycle or loop in linked list

Find out loop or cycle in linked list in java


Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions

Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

Unknown said...

Thank you for another fantastic posting. Where else could anyone get that kind of information in such a perfect way of writing? I have a speech next week, and I was looking for more info.
kizidaily , juegosfrivas , friv2gamers

Beatrise said...

Thanks for sharing your information with everyone and keep posting

sherin said...

more informative post
how to enter steam wallet code

Anonymous said...

Read the article if you still don't know whether you need to file w2 form or not.

Sophie Grace said...

Thanks for the best blog was very useful for me. Keep sharing such ideas in the future as well. Thanks for giving me the useful information. webstagram

Shivam Kumar said...

Thanku for sharing such good post.keep this work up. visit LinkedList example

Shivam Kumar said...

Thanku for sharing such good post.keep this work up. visit LinkedList example

Jack sparrow said...

That is nice article from you , this is informative stuff . Hope more articles from you . I also want to share some information about online devops training and devops online training

nirjonniyaz said...

토토사이트검증 토토 먹튀 검증 저희 먹튀커머스 는 2016년 5월 부터 지금까지 먹튀커머스 를 믿고 방문 해주시는 유저 분들을 위해 더이상 먹튀 없는 공정한 배팅 문화 를 만들기 위해서 항상 노력하고 유저분들에 소리에 귀를 기울리는 NO.1 먹튀검증 커뮤니티 입니다. 또한 먹튀커머스 에서는 무분별한 배팅사이트 들을 일방적으로 추천 하지 않고 철저한 검수 작업을 토대로 사전에 먹튀 사고가 발생 안되게끔 유저 분들 에게 추천하는 만큼 저희측에 등록 되어 있는 배팅사이트 내에서 혹여 먹튀가 발생 한다면 오로지 그책임은 저희 먹튀커머스 에 있음을 알려 드립니다. / 먹튀 검증

Unknown said...

This article will outline all the different strategies you should be aware of when it comes to soccer.

best ias coaching in india

Diyalabs said...

Thanks for sharing such a helpful, and understandable blog. I really enjoyed reading it.

Robots for kids
Robotic Online Classes
Robotics School Projects
Programming Courses Malaysia
Coding courses
Coding Academy
coding robots for kids
Coding classes for kids
Coding For Kids

먹튀사이트 said...

Please let me know if you’re looking for a article writer for your site. You have some really great posts and I feel I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some material for your blog in exchange for a link back to mine. Please send me an email if interested. Thank you 먹튀사이트 I couldn't think of this, but it's amazing! I wrote several posts similar to this one, but please come and see!!

unknown said...

What a nice post! I'm so happy to read this. 안전놀이터모음 What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.

Valluva said...

Thank you for sharing
Thanks For Your Blog

oncasinosite said...

Interesting, I saw your article on google, very interesting to read. I have seen this blog, it is very nice to read and has more informative information. Feel free to visit my website; 온라인카지노

casinositelink said...

Hi very nice blog!! Man .. Beautiful .. Wonderful ..I’ll bookmark your web site and take the feeds also. I am glad to search out so many useful information here in the post, thank you for sharing. Feel free to visit my website; 온라인카지노

oncasinositenet said...

Hi ! this is often nice article you shared with great information. Thanks for giving such an exquisite informative information. Feel free to visit my website; 바카라사이트

bacarasite said...

Great web site. A lot of useful information here. I’m sending it to several friends ans also sharing in delicious. And obviously, thanks in your effort! Feel free to visit my website; 온라인카지노

unknown said...

Hello, I am one of the most impressed people in your article. 안전놀이터추천 I'm very curious about how you write such a good article. Are you an expert on this subject? I think so. Thank you again for allowing me to read these posts, and have a nice day today. Thank you.