Comparing two arrayLists from CSV

Leemi :

I have a general question:

What would be the best way to sort two arraylists based on the values of each other if:

(1) each arrayList contains exactly one column of the imported CSV (via inputStream and bufferReader (for sake of easiness, i will not print this below).

//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) for further clarity, each column of the CSV [colOne [1], colOne [2] contain the following information:

//colOne [1]  colOne [2]
   date        value
   friday       32
   tues         21
   wed          5

(3) The way i would to sort it would be like this (by value):

//colOne [1]  colOne [2]
   date        value
   wed          5
   tues         21
   friday       32

(4) I don't find a comparator class to be efficient, as i don't need to write information to the constructor of the arraylist. The list is prefixed by the CSV.

(3) How would be the best way to compare the two lists?

Eritrean :

If your csv contains only one row per date you could store your data to map instead of list:

Map<String,Integer> myMap = new HashMap<>();
String line;
while((line = reader.readLine()) != null) {
    myMap.put(line.split(",")[0], Integer.parseInt(line.split(",")[1]));
}

Afterwards you can sort your 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));

and to print your sorted map:

sorted.entrySet().forEach(System.out::println);

Or as commented by DodgyCodeException read your lines to List<String[]>:

List<String[]> myList = new ArrayList<>();
    String line = "";
    while((line = reader.readLine()) != null) {
        myList.add(line.split(","));
}

and sort:

    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]));
        }
    });

And finally to print your list just use a for loop, for example:

for(String[] row : myList){
    System.out.println(row[0] +" : "+ row[1])
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79229&siteId=1