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.
- 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
}
}
Thanks for sharing.😊
This will help