我有一个CSV文件,我需要按两列对内容进行排序。第一列是日期,第四列是文本。我需要按第一和第四列排序的文件。 我正在尝试这样:
//i read file and iterate in lines
PriorityQueue<String[]> linesOrdenered = new PriorityQueue<>(new LineComparator());
while ((line = br.readLine()) != null) {
String[] row = line.split(CVS_SPLIT_BY);
if ((!isHeader) && row[0].equals("Route Date")) {
header = line;
isHeader = true;
continue;
}
linesOrdenered.add(row);
}
public class LineComparator implements Comparator<String[]> {
//string[3] == key
@Override
public int compare(String[] strings, String[] t1) {
int keyComparator = 0;
try {
Date dataOne = format.parse(strings[0]);
Date dataTwo = format.parse(t1[0]);
keyComparator = dataOne.compareTo(dataTwo);
} catch (ParseException e) {
LOGGER.error("Error on parse Data [{}]", e.getMessage());
}
if (keyComparator == 0) {
keyComparator = strings[3].compareTo(t1[3]);
}
return keyComparator;
}
}
结果是一个PriorityQueue,其中只排序了日期。 CSV文件的示例内容:
12/01/2018,6:30,C-993BNT,A1001
12/03/2018,6:30,C-993BNT,A1001
12/04/2018,6:30,C-993BNT,A1001
12/05/2018,6:30,C-993BNT,A1001
12/01/2018,6:30,C-555BQJ,A1003
12/03/2018,6:30,C-555BQJ,A1003
12/04/2018,6:30,C-555BQJ,A1003
12/05/2018,6:30,C-555BQJ,A1003
12/06/2018,6:30,C-555BQJ,A1003
12/07/2018,6:30,C-555BQJ,A1003
答案 0 :(得分:0)
您的输入文件和“格式”对我们不可用,但据我推测,使用格式进行解析时,所有日期都是不同的(至少在比较它们不返回0的范围内)。
答案 1 :(得分:0)
继续假设Roy Shahaf的想法:
private static DateFormat format = new SimpleDateFormat("MM/dd/yyyy");
我得到:
12/01/2018,6:30,C-993BNT,A1001
12/01/2018,6:30,C-555BQJ,A1003
12/03/2018,6:30,C-993BNT,A1001
12/03/2018,6:30,C-555BQJ,A1003
12/04/2018,6:30,C-993BNT,A1001
12/04/2018,6:30,C-555BQJ,A1003
12/05/2018,6:30,C-993BNT,A1001
12/05/2018,6:30,C-555BQJ,A1003
12/06/2018,6:30,C-555BQJ,A1003
12/07/2018,6:30,C-555BQJ,A1003
对我来说看起来不错。参见https://jdoodle.com/a/QXP