Kemat Rochi Kemat Rochi - 21 days ago 9
Java Question

How to print two ArrayLists to a csv file with multiple columns?

I have two array lists like shown below,

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;

class Reader {
public static void main(String args[]) throws FileNotFoundException {

ArrayList<String> animal = new ArrayList<>();
animal.add("Dog");
animal.add("Cat");
animal.add("Mouse");

ArrayList<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= 15; i++) {
numbers.add(i);
}

PrintWriter writer = new PrintWriter("animals.csv");

for (String ani : animal) {
writer.println(ani + ",");
}

writer.close();
}
}


I want the output to be like this in the .csv file.

Dog,1,2,3,4,5,
Cat,6,7,8,9,10,
Mouse,11,12,13,14,15,


When I use for-loops, the output of the array lists gets printed one below the other in the .csv file.

How do I format the array lists the way I desired, so it looks like this in Excel?
enter image description here

Answer

use writer.print() instead of writer.println()

Notice 'ln' in the method name you are using, which means print line.


Update: To also add numbers along with animal:

public static void main(final String[] args) throws FileNotFoundException {
    ArrayList<String> animal = new ArrayList<>();
    animal.add("Dog");
    animal.add("Cat");
    animal.add("Mouse");

    ArrayList<Integer> numbers = new ArrayList<>();
    for (int i = 1; i <= 15; i++) {
        numbers.add(i);
    }

    PrintWriter writer = new PrintWriter("animals.csv");

    List<String> row = new ArrayList<>();
    int i = 0;
    for (String ani : animal) {
        row.add(ani);
        for (int j = 0; j < 5; j++) {
            row.add(String.valueOf(numbers.get(i++)));
        }
        writer.println(String.join(",", row));
        row.clear();
    }

    writer.close();
}
Comments