java csv 日期,基于列的日期排序java的csv文件

本文介绍如何对CSV文件中按日期列进行排序,分享了原始代码实现及其存在的问题,重点在于解释为何记录数量减少,并提供一个安全的迭代方法来避免并发修改异常。通过实例说明正确处理ArrayList中元素删除的操作技巧。
摘要由CSDN通过智能技术生成

Need to sort a csv file based on the date column. This is how the masterRecords array list looks like

GBEP-1-2-4,FRAG,PMTypeEthernet,NEND,TDTN,15-MIN,Dec 15 2014 - 07:15:00 AM MYT,+0,COMPL

GBEP-1-2-1,FRAG,PMTypeEthernet,NEND,TDTN,15-MIN,Dec 15 2014 - 07:00:00 AM MYT,+0,COMPL

GBEP-2-2-1,FRAG,PMTypeEthernet,NEND,TDTN,15-MIN,Dec 15 2014 - 07:30:00 AM MYT,+0,COMPL

I need to sort it out based from the date 07:15:00, 07:30:00, etc. I created a code to sort it out:

// Date is fixed on per 15min interval

ArrayList sortDate = new ArrayList();

sortDate.add(":00:");

sortDate.add(":15:");

sortDate.add(":30:");

sortDate.add(":45:");

BufferedWriter bw = new BufferedWriter(new FileWriter(tempPath + filename));

for (int k = 0; k < sortDate.size(); k++) {

String date = sortDate.get(k);

for (int j = 0; j < masterRecords.size(); j++) {

String[] splitLine = masterRecords.get(j).split(",", -1);

if (splitLine[10].contains(date)) {

bw.write(masterRecords.get(j) + System.getProperty("line.separator").replaceAll(String.valueOf((char) 0x0D), ""));

masterRecords.remove(j);

}

}

}

bw.close();

You can see from above it will loop thru a first array (sortDate) and loop thru again on the second array which is the masterRecord and write it on a new file. It seems to be working as the new file is sorted out but I notice that my masterRecord has 10000 records but after creating a new file the record shrinks to 5000, Im assuming its how I remove the records from the master list. Anyone knows why?

解决方案

Is not safe to remove an item inside of a loop.

You have to iterate array over Iterator, for example:

List names = ....

Iterator i = names.iterator();

while (i.hasNext()) {

String s = i.next(); // must be called before you can call i.remove()

// Do something

i.remove();

}

The documentation says:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值