List in java and how to iterate.

  • List is the data structure , which keeps the insertion order preserve
  • It allows to store duplicate elements .

List is the interface and it has multiple implementations :

Two popular implementations are below.

  • ArrayList
  • LinkedList

Let's see how we can create a list .

  List<String> al = new ArrayList<>();
		al.add("rajanikanta");
		al.add("Srikanth");
		al.add("suman");
		al.add("saroj");
		al.add("deepak");
		

Different ways of Iterating a List:

  • Using for loop
  • Using enhanced for loop
  • Using Iterator
  • Using java 8 forEach

Using for loop:

for (int i = 0; i < al.size(); i++) {
			System.out.println(al.get(i));


		}

Using enhanced for loop:

for (String name : al) {
			System.out.println(name);
		

}

Using Iterator:

Iterator<String> itr=al.iterator();
		while(itr.hasNext()) {
			String name=itr.next();
			System.out.println(name);

		}

Using java 8 forEach:

al.forEach(x -> System.out.println(x));


How to remove and add elements while Iteration:

  • Using enhanced for loop we can not add and remove elements to the existing list , if we will do so it will leads to ConcurrentModificationException as below.
No alt text provided for this image
  • Using for loop and Iterator and ListIterator we can add or remove elements from list.

Example using for loop:

for (int i = 0; i < al.size(); i++) {
			if (al.get(i).equals("suman")) {
				al.add("akshay");
			
}
		}

Example using Iterator:

Iterator<String> itr = al.iterator();
		while (itr.hasNext()) {
			String name = itr.next();
			if (name.equals("suman")) {
				itr.remove();
				// Here we can not do like al.remove("suman")
				// We will get ConcurrentModificationException
			}

		}


To view or add a comment, sign in

More articles by Rajanikanta Pradhan

  • Understanding Time Complexity: The Key to Efficient Algorithm Design

    What is time complexity ? Time complexity of an algorithm quantifies the amount of time taken by an algorithm to run…

  • The SOLID Principles

    The aim of the SOLID principles is to reduce dependencies, enabling the ability to change code in one area of an…

  • Fail-Fast and Fail-Safe Iterators in Java

    Concept Of the Day: Fail-Fast and Fail-Safe Iterators in Java: Iterators are used in Collection framework in Java to…

  • Isolation Levels and Spring Transaction

    while Performing Database operation we can face some problems: like DirtyRead Problem:- Dirty readproblem means Reading…

  • Annotations in java

    Annotations :- It's a form of metadata, provide data about a program that is not part of the program itself…

  • Jax-Rs Application Deployment and Runtime Environments

    There are multiple deployment options in the Servlet container for a JAX-RS application. 1.

Explore content categories