[java] Print ArrayList

I have an ArrayList that contains Address objects.

How do I print the values of this ArrayList, meaning I am printing out the contents of the Array, in this case numbers.

I can only get it to print out the actual memory address of the array with this code:

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.print(houseAddress.get(i));
}  

This question is related to java arrays printing arraylist

The answer is


This helped to me:

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

Simplest way to print an ArrayList is by using toString

List<String> a=new ArrayList<>();
    a.add("111");
    a.add("112");
    a.add("113");
    System.out.println(a.toString());

Output

[111, 112, 113]


public void printList(ArrayList<Address> list){
    for(Address elem : list){
        System.out.println(elem+"  ");
    }
}

since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object

solution in your Address class override the toString() method like this

public class Address {

int addressNo ; 
....
....
...

protected String toString(){
    return Integer.toString(addressNo);
}

now when you call

houseAddress.get(i)  in the `System.out.print()` method like this

System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called


Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.print(houseAddress.get(i).toString());
} 

A general example:

ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]

Are you saying that ArrayList is storing addresses of arrays because that is what is returning from the toString call, or because that's actually what you're storing?

If you have an ArrayList of arrays (e.g.

int[] arr = {1, 2, 3};
houseAddress.add(arr);

Then to print the array values you need to call Arrays.deepToString:

for (int i = 0; i < houseAddress.size(); i++) {
     System.out.println(Arrays.deepToString(houseAddress.get(i)));
}

I am not sure if I understood the notion of addresses (I am assuming houseAddress here), but if you are looking for way a to print the ArrayList, here you go:

System.out.println(houseAddress.toString().replaceAll("\\[\\]", ""));

You can even use an enhanced for loop or an iterator like:

for (String name : houseAddress) {
    System.out.println(name);
}

You can change it to whatever data type houseAddress is and it avoids unnecessary conversions


You can simply give it as:

System.out.println("Address:" +houseAddress);

Your output will look like [address1, address2, address3]

This is because the class ArrayList or its superclass would have a toString() function overridden.

Hope this helps.


You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress has values of data type String

Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
    out.println(iterator.next());
}

Note : You can even use an enhanced for loop for this as mentioned by me in another answer


From what I understand you are trying to print an ArrayList of arrays and one way to display that would be

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

if you make the @Override public String toString() as comments, you will have the same results as you did. But if you implement your toString() method, it will work.

public class PrintingComplexArrayList {

public static void main(String[] args) {
    List houseAddress = new ArrayList();
    insertAddress(houseAddress);
    printMe1(houseAddress);
    printMe2(houseAddress);
}

private static void insertAddress(List address)
{
    address.add(new Address(1));
    address.add(new Address(2));
    address.add(new Address(3));
    address.add(new Address(4));
}
private static void printMe1(List address)
{
    for (int i=0; i<address.size(); i++)
        System.out.println(address.get(i));
}

private static void printMe2(List address)
{
    System.out.println(address);
}

}

class Address{ private int addr; public Address(int i) { addr = i; }

@Override public String toString()
{
    Integer iAddr = new Integer (addr);
    return iAddr.toString();
}

}


Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below

for(int i = 0; i < houseAddress.size(); i++) {
    System.out.print((houseAddress.get(i)).toString());
}

Make sure you have a getter in House address class and then use:

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.print(houseAddress.get(i)**.getAddress()**);
}

JSON

An alternative Solution could be converting your list in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString(). Additionaly it works for any other Object or Collection on the fly.

Example using Google's Gson:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

...
public static void printJsonString(Object o) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    /*
     * Some options for GsonBuilder like setting dateformat or pretty printing
     */
    Gson gson = gsonBuilder.create();
    String json= gson.toJson(o);
    System.out.println(json);
}

you can use print format if you just want to print the element on the console.

for(int i = 0; i < houseAddress.size(); i++) {   
    System.out.printf("%s", houseAddress.get(i));
}  

Add toString() method to your address class then do

System.out.println(Arrays.toString(houseAddress));

list.toString() is good enough.

The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.


assium that you have a numbers list like that

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

if you print the list

//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
    System.out.print(number);
}

//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));

//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));


//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);

Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:

With annonymous class:

houseAddress.forEach(new Consumer<String>() {
    @Override
    public void accept(String s) {
        System.out.println(s);
    }
}); 

lambda expression:

houseAddress.forEach(s -> System.out.println(s));

or by using method reference:

houseAddress.forEach(System.out::print);

This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.


This is a simple code of add the value in ArrayList and print the ArrayList Value

public class Samim {

public static void main(String args[]) {
    // Declare list
    List<String> list = new ArrayList<>();

    // Add value in list
    list.add("First Value ArrayPosition=0");
    list.add("Second Value ArrayPosition=1");
    list.add("Third Value ArrayPosition=2");
    list.add("Fourth Value ArrayPosition=3");
    list.add("Fifth Value ArrayPosition=4");
    list.add("Sixth Value ArrayPosition=5");
    list.add("Seventh Value ArrayPosition=6");

    String[] objects1 = list.toArray(new String[0]);

    // Print Position Value
    System.err.println(objects1[2]);

    // Print All Value
    for (String val : objects1) {
        System.out.println(val);
      }
    }
}

 public static void main(String[] args) {
        List<Moyen> list = new ArrayList<Moyen>();
        Moyen m1 = new Moyen();
        m1.setCodification("c1");
        m1.setCapacityManager("Avinash");
        Moyen m2 = new Moyen();
        m2.setCodification("c1");
        m2.setCapacityManager("Avinash");
        Moyen m3 = new Moyen();
        m3.setCodification("c1");
        m3.setCapacityManager("Avinash");

        list.add(m1);
        list.add(m2);
        list.add(m3);
        System.out.println(Arrays.toString(list.toArray()));
    }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to printing

How do I print colored output with Python 3? Print a div content using Jquery Python 3 print without parenthesis How to find integer array size in java Differences Between vbLf, vbCrLf & vbCr Constants Printing variables in Python 3.4 Show DataFrame as table in iPython Notebook Removing display of row names from data frame Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window Print a div using javascript in angularJS single page application

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable