英文:
Add multiple records to List<List<Object>>
问题
我正在尝试向对象的列表列表中添加多个记录,但我不知道该如何做(```java```)。
唯一我发现可能的方法就是直接这样做:
List<List<Object>> values = Arrays.asList(
Arrays.asList("84935", "01/02/2020", "01/02/2020", "已解决", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020"),
Arrays.asList("84936", "02/02/2020", "02/02/2020", "已解决", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020"),
Arrays.asList("84937", "03/02/2020", "03/02/2020", "已解决", "XXX", "XXX", "XXX", "XXX", "1", "1", "15", "0", "2020")
);
我想读取一个 ```.csv``` 文件并将其写入该列表。当我尝试使用 ```.add``` 或 ```set``` 时,我会得到一个空指针异常,我还没有找到解决方法。
是否可以使用循环自动添加记录?由于这是唯一一种 Google Sheets Api 允许的方式,所以列表必须是 ```List<List<Object>>```。
谢谢。
英文:
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
得分: 2
是的,完全可以在循环内部编写列表的列表:
例如:
List<List<String>> list = new ArrayList<>();
for (String line : lines) {
list.add(Arrays.asList(line.split(",")));
}
如果你正在读取CSV文件,最好使用第三方库,比如Apache CSVParser。
然而,如果你坚持自己做:
List<List<String>> fields = Files.lines(fileName)
.map(line -> Arrays.asList(line.split(",")))
.collect(Collectors.toList());
英文:
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());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论