简体   繁体   中英

Skip header of CSV file while reading in core Java with below approach

I want to skip the header from this csv file with the below reading mode approach. Restricting to this mode because I am using Collections.sort which uses List as an argument.

Scenario : I am holding around 20 columns and I need to sort on the 3rd fields, then need to take the average based on 18th col for each key(3rd field). In output only 4 columns is required.

    ------------ skip -------
    File file = new File("C:\\Users\\shekhar\\Desktop\\Lab\\DumpData.csv"); 
    //Declare file
    List<String>  lines = 
    Files.readAllLines(file.toPath(),StandardCharsets.UTF_8);//Reading file     
    Collections.sort(lines,new EmpIdComparator1()); // Sorting on 3rd field using comparator
    Map<String,List<String>> employeeById = new HashMap<>();  // Map used to decrease the column 
    ------------ skip ----------------------------------

Input Data is given below in comma separated value format:

    Employee Name,Employee ID,Working Hours,Date,<more columns >
    ===========================================
    Sam,002,6.5,1 Nov
    Sam,002,8,2 Nov

为什么不只是在您的collections.sort之前通过遍历原始列表创建新的List数组,而是使用变量if(lineno> 2){.....为list array添加代码}忽略第一行,然后执行排序在这个新阵列上,而不是原来的阵列上。

我会说基于您的员工编号使用比较器,因此排序仅在员工编号000以上的值上发生。

Sublist does what you want, I think.

Collections.sort(lines.sublist(1, lines.size()),new EmpIdComparator1());

It only sorts the part, or view, of the list that you are passing into the method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM