首页 > 解决方案 > 比较 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) 比较这两个列表的最佳方法是什么?

标签: javaarrayssortingarraylist

解决方案


如果您的 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])
}

推荐阅读