Izzy
Izzy

Reputation: 6866

How to print a List into a table format

I'm in the process of learning Java and Have a very simple requirement which I can't seem to figure out where I'm going wrong. A simple ArrayList which writes to console

FirstName

SurName

Dob

ArrayList<String> myList = new ArrayList<String>();
    
myList.add("FirstName");
myList.add("Another FirstName");
myList.add("SurName");
myList.add("Another SurName");
myList.add("Dob");
myList.add("Another Dob");

I can't seem to figure out how can I print them in one line i.e

FirstName Surname Dob

Another FirstName Another SurName Another Dob

Thanks in advance for all your help.

Upvotes: 1

Views: 9312

Answers (3)

Adam
Adam

Reputation: 36703

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

myList.add("FirstName");
myList.add("Another FirstName");
myList.add("John");

myList.add("SurName");
myList.add("Another SurName");
myList.add("Smith");

myList.add("Dob");
myList.add("Another Dob");
myList.add("31/1/1994");

int stride = myList.size() / 3;
for (int row = 0; row < myList.size() / 3; row++) {
    System.out.println(String.format("%20s %20s %12s", myList.get(row),
            myList.get(row + stride), myList.get(row + stride * 2)));
}

Output

        FirstName              SurName          Dob
Another FirstName      Another SurName  Another Dob
             John                Smith    31/1/1994

Upvotes: 4

David Conrad
David Conrad

Reputation: 16359

If the entries for a single individual were adjacent to one another, you could go through the list printing two items with System.out.print and the third with System.out.println, but what you really need to do is create a Person class with first name, surname, and date of birth fields, a toString() method that returns all of those in a single string, and then you can iterate over your ArrayList<Person> and print each one out with System.out.println:

List<Person> people = /* ... */;
for (Person person : people) {
    System.out.println(person);
}

Or, in Java 8:

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

Upvotes: 0

ThePerson
ThePerson

Reputation: 3236

for(String listItem : myList){
    System.out.print(listItem);
}

This is your answer. It will loop around, and each time it goes round the loop listItem will be equal to an element from the list, and it will print it using System.out.print.

Upvotes: 0

Related Questions