我有一个一般性问题:
在以下情况下,根据彼此的值对两个数组列表进行排序的最佳方法是什么:
(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) 我没有发现比较器类是高效的,因为我不需要将信息写入 arraylist 的构造函数。该列表以 CSV 为前缀。
(3) 比较两个列表的最佳方式是什么?
最佳答案
如果您的 csv 每个日期只包含一行,您可以将数据存储到 map 而不是列表:
Map<String,Integer> myMap = new HashMap<>();
String line;
while((line = reader.readLine()) != null) {
myMap.put(line.split(",")[0], Integer.parseInt(line.split(",")[1]));
}
之后您可以对 map 进行排序:
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));
并打印您的排序 map :
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])
}
关于java - 比较来自 CSV 的两个数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53484731/