OpenCSV - How to map selected columns to Java Bean regardless of order?

前端 未结 10 927
终归单人心
终归单人心 2020-11-30 06:38

I have a CSV file with the following columns: id, fname, telephone, lname, address.

I have a P

10条回答
  •  无人及你
    2020-11-30 07:20

    You can use HeaderColumnNameTranslateMappingStrategy. Lets assume your CSV has the following columns: Id, Fname, Telephone, Lname, Address for the sake of simplicity.

    CsvToBean csvToBean = new CsvToBean();
    
    Map columnMapping = new HashMap();
    columnMapping.put("Id", "id");
    columnMapping.put("Fname", "fname");
    columnMapping.put("Lname", "lname");
    
    HeaderColumnNameTranslateMappingStrategy strategy = new HeaderColumnNameTranslateMappingStrategy();
    strategy.setType(Person.class);
    strategy.setColumnMapping(columnMapping);
    
    List list = null;
    CSVReader reader = new CSVReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("test.csv")));
    list = csvToBean.parse(strategy, reader);
    

    The columnMapping will map the columns with your Person object.

提交回复
热议问题