How to sort CSV file by two columns? Right now I am able to sort it by one column. I need to sort it by first two columns. How to do it? Here is the code that I am using for sorting it by its first column:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Practice {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("sample-input.csv"));
Map<String, List<String>> map = new TreeMap<String, List<String>>();
String line = reader.readLine();//read header
while ((line = reader.readLine()) != null) {
String key = getField(line);
List<String> l = map.get(key);
if (l == null) {
l = new LinkedList<String>();
map.put(key, l);
}
l.add(line);
}
reader.close();
FileWriter writer = new FileWriter("output.csv");
writer.write("Symbol, Exchange, Minimum, Average, Maximum, Total
");
for (List<String> list : map.values()) {
for (String val : list) {
writer.write(val);
writer.write("
");
}
}
writer.close();
}
private static String getField(String line) {
return line.split(",")[0];
// extract value you want to sort on
}
}
EDIT: The output after two column sort becomes like:
ABC,X,0.10,10
ABC,X,0.09,20
ABC,X,0.11,10
ABC,X,0.11,20
ABC,X,0.10,10
ABC,Y,0.09,10
ABC,Y,0.08,10
ABC,Z,0.12,15
ABC,Z,0.10,15
DEF,X,0.17,10
DEF,X,0.14,10
DEF,Y,0.15,15
DEF,Y,0.15,15
DEF,Y,0.17,15
DEF,Y,0.16,15
DEF,Y,0.17,15
DEF,Z,0.14,10
DEF,Z,0.15,10
I need the output like this:
ABC,X,0.09,0.11
ABC,X,0.09,0.11
ABC,X,0.09,0.11
ABC,X,0.09,0.11
ABC,X,0.09,0.11
ABC,Y,0.08,0.9
ABC,Y,0.08,0.9
ABC,Z,0.10,0.12
ABC,Z,0.10,0.12
DEF,X,0.14,0.17
DEF,X,0.14,0.17
DEF,Y,0.15,0.17
DEF,Y,0.15,0.17
DEF,Y,0.15,0.17
DEF,Y,0.15,0.17
DEF,Y,0.15,0.17
DEF,Z,0.14,0.15
DEF,Z,0.14,0.15
But, I want the third column to display the minimum of the values for X, then min value for Y, and then Z from the values that are currently being displayed in the third column.
See Question&Answers more detail:
os