首页 > 解决方案 > 从 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

感谢您的关注。

标签: javalistarraylist

解决方案


假设客户名称是唯一的,则无需返回 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


推荐阅读