java - 比较 CSV 中的两个数组列表
问题描述
我有一个普遍的问题:
在以下情况下,根据彼此的值对两个数组列表进行排序的最佳方法是什么:
(1) 每个 arrayList 包含导入的 CSV 的一列(通过 inputStream 和 bufferReader (为方便起见,我不会在下面打印)。
//my arrayLists:
List <String> OpenVal = new Arraylist ();
List <String> CloseVal = new Arraylist();
//lists from above contain column 0 and 1 from CSV:
while((reader.readLine()) != null) {
Sting line = "";
String ColTwo [] = line.split(",");
openVal.add(colOne[1]);
closVal.add(colOne[2]);
(2) 为了更清楚起见,CSV [colOne [1], colOne [2] 的每一列都包含以下信息:
//colOne [1] colOne [2]
date value
friday 32
tues 21
wed 5
(3)我排序的方式是这样的(按值):
//colOne [1] colOne [2]
date value
wed 5
tues 21
friday 32
(4) 我发现比较器类效率不高,因为我不需要将信息写入数组列表的构造函数。该列表以 CSV 为前缀。
(3) 比较这两个列表的最佳方法是什么?
解决方案
如果您的 csv 每个日期只包含一行,您可以将数据存储到地图而不是列表:
Map<String,Integer> myMap = new HashMap<>();
String line;
while((line = reader.readLine()) != null) {
myMap.put(line.split(",")[0], Integer.parseInt(line.split(",")[1]));
}
之后,您可以对地图进行排序:
Map<String,Integer> sorted = myMap.entrySet().stream().
sorted(Map.Entry.comparingByValue()).
collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(e1, e2) -> e1,LinkedHashMap::new));
并打印您的排序地图:
sorted.entrySet().forEach(System.out::println);
或者正如 DodgyCodeException 评论的那样,将您的行读为List<String[]>
:
List<String[]> myList = new ArrayList<>();
String line = "";
while((line = reader.readLine()) != null) {
myList.add(line.split(","));
}
并排序:
Collections.sort(myList, new Comparator<String[]>() {
@Override
public int compare(String[] o1, String[] o2) {
return Integer.compare(Integer.parseInt(o1[1]), Integer.parseInt(o2[1]));
}
});
最后要打印您的列表,只需使用 for 循环,例如:
for(String[] row : myList){
System.out.println(row[0] +" : "+ row[1])
}
推荐阅读
- powershell - 从文本文件中删除空格
- java - TextRecognize from image not detecting other language
- google-apps-script - 如何获取另一个电子表格的最后一行并将数据放入其中?
- c# - 我见过很多这样的错误解决方案,但我找不到任何可以帮助我解决这个问题的方法。真的希望你们中的任何人都可以提供帮助。谢谢
- swiftui - 在 Firebase 登录过程中,我应该在哪里检查/迁移现有内容?
- python-3.x - 如何在 python 中修复此语法错误?
- excel - 如何在自动筛选条件值中包含整数
- javascript - 使用延迟加载解析图像
- http - Binance.us order api throwing 'Not all sent parameters were read' 错误
- android-studio - Android Studio Kotlin - 添加、保存和显示多个输入