Print ArrayList

JavaArraysPrintingArraylist

Java Problem Overview


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));
}  

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

Add toString() method to your address class then do

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

Solution 3 - Java

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()));

Solution 4 - Java

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

Solution 5 - Java

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.

Solution 6 - Java

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);

Solution 7 - Java

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)));
}

Solution 8 - Java

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

Solution 9 - Java

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());
}

Solution 10 - Java

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("\\[\\]", ""));

Solution 11 - Java

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.

Solution 12 - Java

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]

Solution 13 - Java

This helped to me:

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

Solution 14 - Java

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

Solution 15 - Java

 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()));
    }

Solution 16 - Java

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

Solution 17 - Java

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();
}

}

Solution 18 - Java

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()**);
}

Solution 19 - Java

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));
}  

Solution 20 - Java

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]

Solution 21 - Java

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);
      }
	}
}

Solution 22 - Java

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);
}

Solution 23 - Java

  1. Add toString() method to your class
  2. houseAddress.forEach(System.out::println);

Solution 24 - Java

Consider using an "Enhanced for loop" I had to do this solution for a scenario in which the arrayList was coming from a class object

changing the String datatype to the appropriate datatype or class object as desired.

ArrayList<String> teamRoster = new ArrayList<String>();

// Adding player names
teamRoster.add("Mike");
teamRoster.add("Scottie");
teamRoster.add("Toni");

System.out.println("Current roster: ");

for (String playerName : teamRoster) {
   System.out.println(playerName);
   // if using an object datatype, you may need to use a solution such as playerName.getPlayer()
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondancooper93View Question on Stackoverflow
Solution 1 - JavaoldoView Answer on Stackoverflow
Solution 2 - JavaAshwinee K JhaView Answer on Stackoverflow
Solution 3 - JavaBen DworkinView Answer on Stackoverflow
Solution 4 - JavaconfuciusView Answer on Stackoverflow
Solution 5 - JavaSurajView Answer on Stackoverflow
Solution 6 - JavaRagulanView Answer on Stackoverflow
Solution 7 - JavaJoshBramlettView Answer on Stackoverflow
Solution 8 - JavaLove BisariaView Answer on Stackoverflow
Solution 9 - Java21stkingView Answer on Stackoverflow
Solution 10 - JavaManuView Answer on Stackoverflow
Solution 11 - JavaMichał SzewczykView Answer on Stackoverflow
Solution 12 - JavaRifaquat SiddiquiView Answer on Stackoverflow
Solution 13 - JavaAbduhafizView Answer on Stackoverflow
Solution 14 - JavaIshan SrivastavaView Answer on Stackoverflow
Solution 15 - JavaAvinash KhadsanView Answer on Stackoverflow
Solution 16 - JavaIshan SrivastavaView Answer on Stackoverflow
Solution 17 - Javauser7194131View Answer on Stackoverflow
Solution 18 - JavagdograView Answer on Stackoverflow
Solution 19 - JavaKenneth Ryan DyView Answer on Stackoverflow
Solution 20 - JavaJacoSolariView Answer on Stackoverflow
Solution 21 - JavaSamim AktarView Answer on Stackoverflow
Solution 22 - JavatobsobView Answer on Stackoverflow
Solution 23 - JavaalphcoderView Answer on Stackoverflow
Solution 24 - JavaJhWebDevView Answer on Stackoverflow