Как вывести список в java
Перейти к содержимому

Как вывести список в java

  • автор:

How to Print a List in Java

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:

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:

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:

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.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Java print ArrayList example

Java print ArrayList example shows how to print ArrayList in Java. The example also shows various ways to print the ArrayList using a loop, Arrays class, and Java 8 Stream.

How to print ArrayList in Java?

There are several ways using which you can print ArrayList in Java as given below.

1) Using for loop

You can print ArrayList using for loop in Java just like an array.

2) Using enhanced for loop

You can also use the enhanced for loop instead of the for loop it iterate over the elements of an ArrayList and print.

3) Using Arrays class

You can convert ArrayList to an array and use the toString method of Arrays class to print the elements.

If you want to remove the square brackets, you can remove them using the replaceAll method as given below.

4) Using Java 8 stream

If you are using Java 8, you can use the stream as given below.

Or you can use below given statement to print the elements of ArrayList.

How to print ArrayList containing custom objects?

How to print ArrayList containing objects of a custom class? For example, consider below given code containing ArrayList of Person class objects.

Instead of printing the contents of the Person objects, our code printed memory locations of the Person object. The reason is since the Person class does not override the toString method, the default toString method of the Object class is called which prints the address location of the object.

Let’s override the toString method in the Person class to get the contents of the Person object instead of the memory locations.

Print an ArrayList in Java

In this article, we’ll go over multiple ways to print an ArrayList in Java. Our Arraylist will contain a class object called ModelClass , which has a variable name and getter/setter functions.

Print Arraylist in Java Using the for Loop

We can print Java ArrayList object’s items using a loop. Here, we use the for loop to go through every ModelClass object inside modeList and call the getName() function, which returns the name.

Print Arraylist in Java Using forEach

In Java, every ArrayList has a forEach method, which is one of the simplest ways to loop through all the items just like the for loop. Like the previous example, we can get the names from ModelClass using the getName() method.

Print Arraylist in Java Using IDs

Every ArrayList element is given a unique ID to identify it; we can get this if we print the ArrayList without using any method like toString() . It will print the raw ArrayList with the item’s IDs, which you can see in the example’s output:

Print Arraylist in Java Using the toString() Command

The last method in this list is overriding a toString() method inside the ModelClass . This function will return the name when we call it using modeList . Take note that this process can only return string values, as implied in its name.

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

How to Print ArrayList in Java

In this article, we will explore different ways of printing an ArrayList in Java. Before that, we should know what is ArrayList and Why we need to use it in creating Java applications. You can refer to my previous blogs in Javahungry to know about ArrayList in Java.

Now, we will start exploring the different ways of printing ArrayList in Java with code examples.
1. Using for loop.
2. Using enhanced for each loop.
3. Using the Iterator interface.
4. Using the ListIterator interface.
5. Using println() method.
6. Using toString() method.
7. Using the forEach method with a lambda expression.
8. Using Stream class
a. forEach method with a double colon lambda expression.
b. forEach println() method.
c. peek() and collect() methods.

8 ways to Print ArrayList in Java

1. Print ArrayList using for loop

In the below code snippet, we have used for loop to iterate and print the String ArrayList objects.

2. Print ArrayList using enhanced for each loop

In the code snippet, we have used enhanced for each loop to iterate and print the String ArrayList objects.

3. Print ArrayList using the Iterator interface

Here in the below code snippet, we have used the iterator ()method from the Iterator interface. This method returns an iterator for the String ArrayList object. The Iterator interface has methods hasNext() to check if the next element is available and return the element using the next() method. Using the Iterator interface, we can traverse only in a forward direction in the list object.

4. Print ArrayList using the ListIterator interface

Here in the below code snippet, we have used listIterator() method from the ListIterator interface. This method returns a list iterator for the String ArrayList object. The Iterator interface has methods hasNext() to check if the next element is available and return the element using the next() method. Using the ListIterator interface, we can traverse in both forward and backward directions in the list object.

5. Print ArrayList using println() method

In the below code snippet, println() method is used to print the ArrayList object directly. ArrayList objects containing primitive data types can be printed directly using println() method.

6. Print ArrayList using toString() method

Here in the below code snippet, we are overriding toString() method to print the custom class ArrayList object. If the toString() method is not overridden ,the compiler prints the memory location of the objects.

If the toString() method is not overridden, the compiler prints the memory location of the objects which will be as,
Output:
Employee names are[Joy, Rose, Employee@2f92e0f4, Employee@28a418fc]
We need to override the toString() method which tells the compiler how to print the custom class objects(here it is employee class). We get the below output after we override the toString() method.
Output:
Employee names are[Joy, Rose, Anil, Mani]

7. Print ArrayList using the forEach() method with a lambda expression

Java 8 gives a new method called forEach method to iterate the elements in the collection objects and Lambda expression to make our code readable and short.
In the below code snippet, we have used the forEach() method with a lambda expression to print the String ArrayList object.

8. Print ArrayList using Stream class (Java 8)

a. forEach method with double colon lambda expression.
b. forEach println() method.
c. peek() and collect() methods.
Java 8 introduces Stream class which provides forEach(), peek()and collect() methods to print the ArrayList object as given in the below code snippet.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *