5

I have to print list of objects to a text file with table format. For example, if I have list of Person(has getName,getAge and getAddress methods)objects, the text file should look like as below.

Name       Age      Address

Abc        20       some address1
Def        30       some address2 

I can do this by manually writing some code, where I have to take care of spaces and formatting issues.

I am just curious whether are they APIs or tools to do this formatting work?

3 Answers 3

8
import java.util.*;

public class Test {

    public static void main(String[] args) {
        List<Person> list = new ArrayList<Person>();
        list.add(new Person("alpha", "astreet", 12));
        list.add(new Person("bravo", "bstreet", 23));
        list.add(new Person("charlie", "cstreet", 34));
        list.add(new Person("delta", "dstreet", 45));

        System.out.println(String.format("%-10s%-10s%-10s", "Name", "Age", "Adress"));
        for (Person p : list)
            System.out.println(String.format("%-10s%-10s%-10d", p.name, p.addr, p.age));
    }
}

class Person {
    String name;
    String addr;
    int age;
    public Person(String name, String addr, int age) {
        this.name = name;
        this.addr = addr;
        this.age = age;
    }
}

Output:

Name      Age       Adress    
alpha     astreet   12        
bravo     bstreet   23        
charlie   cstreet   34        
delta     dstreet   45        
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! This is really simple and effective. Thanks.
0

Use printf with padded fields to achive column alignments.

PrintWriter.printf to be specific

Comments

0

Library for printing Java objects as Markdown / CSV / HTML table using reflection: https://github.com/mjfryc/mjaron-etudes-java

dependencies {
    implementation 'io.github.mjfryc:mjaron-etudes-java:0.2.1'
}
import pl.mjaron.etudes;

class Sample {
    void sample() {
        Cat[] cats = {cat0, cat1};
        Table.render(cats, Cat.class)
            .markdown() // or .csv() or .html()
            .to(System.out) // Or to StrigBuilder | OutputStream | File.
            
            // Optionally specify Left /Right / Center alignment.
            .withAlign(VerticalAlign.Left)
            
            .run(); // Or .runToString() to return it to String.
    }
}

Sample Markdown output:

| name | legsCount | lazy  | topSpeed |
|------|-----------|-------|----------|
| John | 4         | true  | 35.24    |
| Bob  | 5         | false | 75.0     |

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.