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.