Iterating over List Interface in Java
Till now we are having a very small input size and we are doing operations manually for every entity. Now let us discuss various ways by which we can iterate over the list to get them working for a larger sample set.
Methods: There are multiple ways to iterate through the List. The most famous ways are by using the basic for loop in combination with a get() method to get the element at a specific index and the advanced for a loop.
Example:
Java
// Java program to Iterate the Elements // in an ArrayList // Importing java utility classes import java.util.*; // Main class public class GFG { // main driver method public static void main(String args[]) { // Creating an empty Arraylist of string type List<String> al = new ArrayList<>(); // Adding elements to above object of ArrayList al.add( "Geeks" ); al.add( "Geeks" ); // Adding element at specified position // inside list object al.add( 1 , "For" ); // Using for loop for iteration for ( int i = 0 ; i < al.size(); i++) { // Using get() method to // access particular element System.out.print(al.get(i) + " " ); } // New line for better readability System.out.println(); // Using for-each loop for iteration for (String str : al) // Printing all the elements // which was inside object System.out.print(str + " " ); } } |
Geeks For Geeks Geeks For Geeks
List Interface in Java with Examples
The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
Table of Content
- List Interface in Java
- Declaration of Java List Interface
- Example of Java List
- Operations in a Java List Interface
- Complexity of List Interface in Java
- Iterating over List Interface in Java
- Methods of the List Interface
- Java List vs Set
Contact Us