packageexamples;importjava.util.ArrayList;importjava.util.List;publicclassApp{publicstaticvoidmain(String[]args){List<String>names=newArrayList<>();names.add("Harish");names.add("Shanu");names.add("Menaka");names.add("Jim");names.add("Tim");for(inti=0;i<names.size();i++){System.out.print(names.get(i)+" ");//Harish Shanu Menaka Jim Tim
}}}
3. Enhanced for loop
You can use enhanced for loop for printing the ArrayList. Here you do not have to specify any index
while iterating. Code is simple and concise while looping through list.
packageexamples;importjava.util.ArrayList;importjava.util.List;publicclassApp{publicstaticvoidmain(String[]args){List<String>names=newArrayList<>();names.add("Harish");names.add("Shanu");names.add("Menaka");names.add("Jim");names.add("Tim");for(Stringname:names){System.out.print(name+" ");// Harish Shanu Menaka Jim Tim
}}}
4. Using forEach with lambda expression
Here one can use forEach method of collection in Java 8
which applies lambda expression to each element
packageexamples;importjava.util.ArrayList;importjava.util.List;publicclassApp{publicstaticvoidmain(String[]args){List<String>names=newArrayList<>();names.add("Harish");names.add("Shanu");names.add("Menaka");names.add("Jim");names.add("Tim");names.forEach(name->System.out.print(name+" "));//Harish Shanu Menaka Jim Tim
}}
packageexamples;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;publicclassApp{publicstaticvoidmain(String[]args){List<String>names=newArrayList<>();names.add("Harish");names.add("Shanu");names.add("Menaka");names.add("Jim");names.add("Tim");Iterator<String>iterator=names.iterator();while(iterator.hasNext()){System.out.print(iterator.next()+" ");//Harish Shanu Menaka Jim Tim
}}}
6. Using ListIterator
We can traverse Arraylist in both direction using ListIterator as shown in below example.
.hasNext() and .next() moves in forward direction.
.hasPrevious and .previous() moves in backward direction.
packageexamples;importjava.util.ArrayList;importjava.util.List;importjava.util.ListIterator;publicclassApp{publicstaticvoidmain(String[]args){List<String>names=newArrayList<>();names.add("Harish");names.add("Shanu");names.add("Menaka");names.add("Jim");names.add("Tim");ListIterator<String>iterator=names.listIterator();while(iterator.hasNext()){System.out.print(iterator.next()+" ");//Harish Shanu Menaka Jim Tim
}System.out.println();while(iterator.hasPrevious()){System.out.print(iterator.previous()+" ");//Tim Jim Menaka Shanu Harish
}}}
7. Using String.join()
You can format the elements of the Arraylist using String.join() using your own delimiter.
In the below example delmiter ‘|’ is used to separate each element of the list.