Add multiple records to List<List<Object>>

Viewed 133

I'm trying to add multiple records in a List of List of Objects and I don't know how to do it (java).

The only way I've found it possible is by doing it literally:

    List<List<Object>> values = Arrays.asList(
            Arrays.asList("84935", "01/02/2020", "01/02/2020", "resolved", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020"),
            Arrays.asList("84936", "02/02/2020", "02/02/2020", "resolved", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020"),
            Arrays.asList("84937", "03/02/2020", "03/02/2020", "resolved", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020")
            );

I want to read a .csv file and write in it that list. When I try with .add or set I get a nullpointer Exception and I haven't been able to find a solution.

Is it possible to add the records automatically with a loop? It is mandatory that the List is List<List<Object>> because it's the only way that Google Sheets Api allows.

Thank you.

1 Answers

Yes it's absolutely possible to write a list of lists inside a loop:

For example:

List<List<String>> list = new ArrayList<>();
for (String line: lines) {
    list.add(Arrays.asList(line.split(","));
}

If you're reading a CSV file you'd be better off using a third party library such as Apache CSVParser.

However if you insist on doing it yourself:

List<List<String>> fields = Files.lines(fileName)
    .map(l -> Arrays.asList(l.split(",")))
    .collect(Collector.toList());
Related