Loop list in list java

How to traverse iterate or loop ArrayList in Java

Iterating, traversing or Looping ArrayList in Java means accessing every object stored in ArrayList and performing some operations like printing them. There are many ways to iterate, traverse or Loop ArrayList in Java e.g. advanced for loop, traditional for loop with size(), By using Iterator and ListIterator along with while loop etc. All the method of Looping List in Java also applicable to ArrayList because ArrayList is an essentially List. In next section we will see a code example of Looping ArrayList in Java.

Now we know that there are multiple ways to traverse, iterate or loop ArrayList in Java, let’s see some concrete code example to know exactly How to loop ArrayList in Java. I prefer advanced for loop added in Java 1.5 along with Autoboxing, Java Enum, Generics, Varargs and static import, also known as foreach loop if I have to just iterate over Array List in Java. If I have to remove elements while iterating than using Iterator or ListIterator is the best solution.

import java.util.ArrayList ;
import java.util.Iterator ;

/**
* Java program which shows How to loop over ArrayList in Java using advanced for loop,
* traditional for loop and How to iterate ArrayList using Iterator in Java
* advantage of using Iterator for traversing ArrayList is that you can remove
* elements from Iterator while iterating.

Читайте также:  Php для локальной сети

* @author
*/
public class ArrayListLoopExample

public static void main ( String args [])

//Creating ArrayList to demonstrate How to loop and iterate over ArrayList
ArrayList < String > games = new ArrayList < String > ( 10 ) ;
games. add ( «Cricket» ) ;
games. add ( «Soccer» ) ;
games. add ( «Hockey» ) ;
games. add ( «Chess» ) ;

System. out . println ( «original Size of ArrayList : » + games. size ()) ;

//Looping over ArrayList in Java using advanced for loop
System. out . println ( «Looping over ArrayList in Java using advanced for loop» ) ;
for ( String game: games ) <
//print each element from ArrayList
System. out . println ( game ) ;
>

//You can also Loop over ArrayList using traditional for loop
System. out . println ( «Looping ArrayList in Java using simple for loop» ) ;
for ( int i = 0 ; i < games. size () ; i++ )<
String game = games. get ( i ) ;
>

//Iterating over ArrayList in Java
Iterator < String > itr = games. iterator () ;
System. out . println ( «Iterating over ArrayList in Java using Iterator» ) ;
while ( itr. hasNext ()) <
System. out . println ( «removing » + itr. next () + » from ArrayList in Java» ) ;
itr. remove () ;
>

System. out . println ( «final Size of ArrayList : » + games. size ()) ;

Output:
original Size of ArrayList : 4
Looping over ArrayList in Java using advanced for loop
Cricket
Soccer
Hockey
Chess
Looping ArrayList in Java using simple for loop
Iterating over ArrayList in Java using Iterator
removing Cricket from ArrayList in Java
removing Soccer from ArrayList in Java
removing Hockey from ArrayList in Java
removing Chess from ArrayList in Java
final Size of ArrayList : 0

That’s all on How to iterate, traverse or loop ArrayList in Java. In summary use advance for loop to loop over ArrayList in Java, its short, clean and fast but if you need to remove elements while looping use Iterator to avoid ConcurrentModificationException .

Источник

How to loop ArrayList in Java

Earlier we shared ArrayList example and how to initialize ArrayList in Java. In this post we are sharing how to iterate (loop) ArrayList in Java.

There are four ways to loop ArrayList:

Lets have a look at the below example – I have used all of the mentioned methods for iterating list.

import java.util.*; public class LoopExample < public static void main(String[] args) < ArrayListarrlist = new ArrayList(); arrlist.add(14); arrlist.add(7); arrlist.add(39); arrlist.add(40); /* For Loop for iterating ArrayList */ System.out.println("For Loop"); for (int counter = 0; counter < arrlist.size(); counter++) < System.out.println(arrlist.get(counter)); >/* Advanced For Loop*/ System.out.println("Advanced For Loop"); for (Integer num : arrlist) < System.out.println(num); >/* While Loop for iterating ArrayList*/ System.out.println("While Loop"); int count = 0; while (arrlist.size() > count) < System.out.println(arrlist.get(count)); count++; >/*Looping Array List using Iterator*/ System.out.println("Iterator"); Iterator iter = arrlist.iterator(); while (iter.hasNext()) < System.out.println(iter.next()); >> >
For Loop 14 7 39 40 Advanced For Loop 14 7 39 40 While Loop 14 7 39 40 Iterator 14 7 39 40

In the comment section below, Govardhan asked a question: He asked, how to iterate an ArrayList using Enumeration. Govardhan here is the code:

How to iterate arraylist elements using Enumeration interface

import java.util.Enumeration; import java.util.ArrayList; import java.util.Collections; public class EnumExample < public static void main(String[] args) < //create an ArrayList object ArrayListarrayList = new ArrayList(); //Add elements to ArrayList arrayList.add("C"); arrayList.add("C++"); arrayList.add("Java"); arrayList.add("DotNet"); arrayList.add("Perl"); // Get the Enumeration object Enumeration e = Collections.enumeration(arrayList); // Enumerate through the ArrayList elements System.out.println("ArrayList elements: "); while(e.hasMoreElements()) System.out.println(e.nextElement()); > >
ArrayList elements: C C++ Java DotNet Perl

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

Hi Govardhan, I have updated the post and added the code. You can find your answer above in the post. Let me know if you have any further question.

Use two variable, lets call them fastVariable and slowVariable. Move the fastVariable twice the speed of slowVariable. By the time fastVariable reach end of the list slowVariable will be at middle of the list. Thanks.

Hello! So I have two seperate arraylists. I am trying to display both of them on a form, but only one of them is showing up. Is it possible to loop to arrayLists and display them at the same time?

Melly, You can join both the arraylists and then loop the combined arraylist to display all the elements. Refer this: How to join ArrayList?

Источник

3 Examples to Loop over a List in Java — ArrayList, LinkedList or Vector

There are multiple ways to traverse or loop through a List in Java e.g. by using an Iterator, by using an enhanced for loop of Java 5, and not the forEach() method of Java 8. Given a List is an index-based collection if you know the index you can retrieve an object from a List and because of this, you can also use a traditional for loop which keeps count for iterating a List . Now the question is whether should you use the Iterator or enhanced for loop, or the forEach() method of Java 8 for looping over List in Java .

Well, it depends on what you are doing with the object, if you need to r emove some objects from List then iterating using Iterator is the best choice to a void ConcurrentModificationException, but if you are not removing any element and just doing some operation with each element than enhanced for loop is much cleaner ways to do that.

The main advantage of using enhanced for loop over Iterator is that you don’t need to check for the next element like you need to in the case of Iterator , Java 5 advanced for loop keeps track of size. Also, the code is very clean with no boilerplate.

But, like everything else in the world, you won’t get all benefits, you do have some limitations while loop through a List using enhanced for loop, as shown here.

With the enhanced for loop, you can not modify selective objects as you don’t have an index with you. If you want to selective modify only certain objects then your best bet is to use the traditional for loop which keeps track of indexes.

The third choice is very straightforward, if you are running on Java SE 8 version then there is no reason for not using the forEach() method for looping through a List in Java. It’s lazy and allows you to perform some filtering operation on the stream before fetching an element from the list.

The laziness comes from the Stream class itself. You can check out The Complete Java Masterclass to learn more about the performance benefits provided by lambda expression and stream in Java 8.

3 Examples of looping through a List in Java

Here is a sample Java program that demonstrates How to loop through a List in Java in three different ways, Iterator , for-each loop, and traditional for loop. This technique can be used to loop through Array List or any other index-based List implementation like Vector.

The other two methods like Iterator and enhanced for loop can be used along with any Collection class like HashSet , TreeSet , LinkedHashSet, etc. They are actually the standard way to iterate through the collection in Java.

Java List Iterator Example

The traditional for loop approach is only possible and efficient because of the index-based nature of the List interface, but if you use this with a linked list then you will get worse performance because in LinkedList accessing an element with an index is O(n) operation rather than O(1) operation. This is also the fundamental difference between an ArrayList and LinkedList in Java.

The new method of iterating over a list using the forEach() method is only available in Java SE 8 and I recommend you to read this article to learn how to loop through a list using the forEach() method in Java 8 before you start using them.

Btw, Java SE 8 is full of exciting and more powerful features and it’s essential for a Java developer to learn those features, given it’s the most popular Java version. If you are interested, you should follow a good Java 8 course like What’s New in Java 8 on Pluralsight to learn quickly.

3 ways to loop through a list in Java 8

Alternatively, you can always choose the one from this list of good Java 8 books, earlier published by me.

How to loop over a List in Java

Here is our complete Java program to show you all three ways to loop over a list in Java. You can use these methods to loop over any List like ArrayList, LinkedList, or even Vector in Java.

import java.util.Arrays ;
import java.util.Iterator ;
import java.util.List ;
/**
*
* Java program to demonstrate different ways to loop,
* iterate or traverse List in Java.

* a List in Java.
*
* @author Javin Paul
*/
public class ListLoopExample

public static void main ( String args [])

//First example to iterate List in Java using Iterator
List < String > languages = Arrays. asList ( «Java» ,
«C++» , «Scala» , «Groovy» ) ;

//Getting Iterator from List in Java
Iterator < String > iterator = languages. iterator () ;
System. out . println ( «Iterating List in Java
using Iterator » ) ;

//Iterating through all elements of List
while ( iterator. hasNext ()) <
System. out . printf ( «Current element in List
is %s %n» , iterator. next ()) ;
>

//Second example of Iterating over List in Java
// using a foreach loop

System. out . println ( «Looping List in Java using a
foreach loop» ) ;
for ( String city : languages ) <
System. out . println ( «List Element: » + city ) ;
>

//Third example of Looping List using traditional for loop
for ( int i = 0 ; i < languages. size () ; i++ )<
System. out . printf ( «programming language #%d in
List is : %s %n» , i, languages. get ( i ) ) ;
>

Output:
Iterating List in Java using Iterator
The current element in List is London
The current element in List is Tokyo
The current element in List is NewYork
The current element in List in Mumbai
Looping List in Java using a foreach loop
List Element: London
List Element: Tokyo
List Element: NewYork
List Element: Mumbai
City # 0 in List is: London
City # 1 in List is: Tokyo
City # 2 in List is: NewYork
City # 3 in List is: Mumbai

That’s all on How to iterate or loop over a List in Java. In this Java tutorial, we have seen an example of all three ways of looping List in Java. the first example demonstrates the use of Iterator with List , the second use for loop for looping over List, and the third example uses traditional old for a loop. All this technique can be applied to any index-based List implementation including ArrayList and Vector in Java .

  • How to sort a Map by keys and values in Java? (tutorial)
  • Top 10 Courses to learn Java for Beginners (best courses)
  • How to sort an ArrayList in ascending and descending order in Java? (tutorial)
  • Difference between ArrayList and HashSet in Java? (answer)
  • Top 5 Courses to learn Java Collections and Stream (courses)
  • What is the difference between TreeMap and TreeSet in Java? (answer)
  • Top 10 courses to learn Python for Beginners (courses)
  • The difference between HashSet and TreeSet in Java? (answer)
  • 7 Best Courses to learn Data Structure and Algorithms (best courses)
  • 10 Free courses to learn Java in-depth (courses)
  • The difference between HashMap and ConcurrentHashMap in Java? (answer)
  • 10 courses to learn Data Structure in-depth (courses)
  • The difference between HashMap and LinkedHashMap in Java? (answer)
  • 20+ basic algorithms interview questions for programmers (questions)
  • Top 5 Courses to become full-stack Java developer (courses)
  • The difference between Hashtable and HashMap in Java? (answer)
  • 50+ Core Java Interview Questions and Answers (questions)
  • The difference between ArrayList and LinkedList in Java? (answer)
  • Top 5 Courses to learn Spring Framework in-depth (courses)
  • The difference between Vector and ArrayList in Java? (answer)

P. S. — If you are keen to learn Java Programming in-depth but looking for free online courses then you can also check out Java Tutorial for Complete Beginners (FREE) course on Udemy. It’s completely free and you just need an Udemy account to join this course.

Источник

Оцените статью