How to print out all the elements of a List in Java?

The following is compact and avoids the loop in your example code (and gives you nice commas):

System.out.println(Arrays.toString(list.toArray()));

However, as others have pointed out, if you don't have sensible toString() methods implemented for the objects inside the list, you will get the object pointers (hash codes, in fact) you're observing. This is true whether they're in a list or not.


Since Java 8, List inherits a default "forEach" method which you can combine with the method reference "System.out::println" like this:

list.forEach(System.out::println);

Here is some example about getting print out the list component:

public class ListExample {

    public static void main(String[] args) {
        List<Model> models = new ArrayList<>();

        // TODO: First create your model and add to models ArrayList, to prevent NullPointerException for trying this example

        // Print the name from the list....
        for(Model model : models) {
            System.out.println(model.getName());
        }

        // Or like this...
        for(int i = 0; i < models.size(); i++) {
            System.out.println(models.get(i).getName());
        }
    }
}

class Model {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Tags:

Java

List