java - 从 csv 文件(如 Arraylist.add)向列表添加元素
问题描述
这是我的代码:
public static Map<String, List<Customer>> readCustomerData() throws IOException {
Map<String, List<Customer>> customers =
Files.lines(Paths.get("customer.csv"))
.map(line -> line.split("\\s*,\\s*"))
.map(field -> new Customer(
Integer.parseInt(field[0]), field[1],
Integer.parseInt(field[2]), field[3]))
.collect(Collectors
.groupingBy(Customer::getName));
System.out.println (customers);
return customers;
}
我注意到这段代码将我在 csv 文件中的数据读取到一个元素中,如下所示:
(Ali = ["1 Ali 1201345673 Normal"] , Siti = ["2 Siti 1307891435 Normal"])
但在我的想法中,我想读取数组列表之类的数据,例如对于 Ali:1 是一个元素,Ali 是一个元素,1201345673 是一个元素,Normal 是 Map 客户列表中的另一个元素。我怎样才能修改我的代码来做这样的事情?
这是我的客户课程,以防万一:
public class Customer {
private int customerNo;
private String name;
private int phoneNo;
private String status;
public Customer () {}
public Customer (int customerNo, String name, int phoneNo, String status){
this.customerNo = customerNo;
this.name = name;
this.phoneNo = phoneNo;
this.status = status;
}
public String getName(){
return name;
}
public String toString(){
return customerNo + " " + name + " " + phoneNo + " " + status;
}
这是我的 csv 文件:
1,Ali,1201345673,Normal
2,Siti,1307891435,Normal
感谢您的关注。
解决方案
假设客户名称是唯一的,则无需返回 a Map<String, List<Customer>>
,因为每个List
都包含一个Customer
.
您可以将代码更改为:
Map<String, Customer> customers =
Files.lines(Paths.get("customer.csv"))
.map(line -> line.split("\\s*,\\s*"))
.map(field -> new Customer(
Integer.parseInt(field[0]), field[1],
Integer.parseInt(field[2]), field[3]))
.collect(Collectors.toMap(Customer::getName, Function.identity()));
如果名称不是唯一的,您可以按客户 ID 为客户编制索引。
至于I would like to read the data like the array list such as for Ali: 1 is an element , Ali is an element , 1201345673 is an element and Normal is another element in the list in the Map customer
- 这对我来说没有意义。您已经从输入的每一行创建了一个对象,与 a of 属性Customer
相比,它更有用且类型安全。List
推荐阅读
- c# - 主键值之一的类型与实体中定义的类型不匹配
- python - 沉默后无法恢复粗壮
- java - 从 DB 填充微调器,检索选定的微调器值并保存到 SQL DB
- mysql - 优化子查询以获得更好的性能?
- ios - 访问 From 和 To 邮件名称的 API 响应
- jsp - 如何在JSP中解析JSON数组并形成一个字符串
- r - ggridges 中的计算变量
- c - 未初始化的值是由堆栈分配矩阵 mult 创建的
- ubuntu - 在 omnet++ 中构建 INET 时出错
- angularjs - 无法在 Eclipse IDE 中使用 http get 请求在 angularjs 中获取数据