This write-up will specifically discuss the method of printing a list in Java.
How to Print a List in Java?
To print a List in Java, you can use:
- toString() method
- for loop
- for-each loop
Let’s check out each of the mentioned methods one by one!
Method 1: Print a List in Java Using toString() Method
The “toString()” method can be used to print a list in Java. This method prints the specified list elements directly using their references.
Example
First, we will create a list of String type named “gadgetList” using the Java collection ArrayList:
Then, we will add the values to the list with the help of the “add()” method:
gadgetList.add("Computer");
gadgetList.add("Laptop");
gadgetList.add("Headphones");
Now, we will call the “toString()” method to print the list on the console with the help of “System.out.println()” method:
Output
Want to perform the same operations using loops? Head towards the next sections!
Method 2: Print a List in Java Using for Loop
The most common method to print the List in Java is using a “for” loop. The for loop iterates over the list until its size and prints out the values using the “System.out.println()” method.
Example
In this example we consider the same list named “gadgetList” and print its values using “for” loop:
System.out.println( gadgetList.get(i) );
}
The given output indicates that we have successfully displayed the list values with the help of the “for” loop:
Method 3: Print a List in Java Using for-each Loop
The “for-each” loop can also be utilized for the same purpose. It contains a variable with the same type as the List, colon, and the list’s name. This loop saves elements in the loop variable later printed on the console.
Example
In this example, we print the list named “gadgetList” using a “for-each” loop. So, we will create a String type variable named “gadgets”. Then, print the elements of the list using the “System.out.println()” methods:
System.out.println(gadgets);
}
Output
We have offered all of the essential methods related to printing a list in Java.
Conclusion
To print a list in java, you can use three approaches: for loop, for-each loop, and toString() method. The for loop iterates over the list until its size and prints out the values using the System.out.println() method. The for-each loop contains a variable the same type as the List, colon, and the list’s name and saves elements in the loop variable. Lastly, the toString() method directly prints the specified list elements using their references. This write-up discussed the methods for printing a list in Java.