0

I need to sort a csv file by the third column, but I'm stuck and I can't find a solution.

Code:

import java.util.*;
import java.io.*;
public class SalesStatistics{
public static void main(String[] args){

String filePath = "Filepath";

ArrayList<String> csvValues = new ArrayList<String>();
try{

BufferedReader br = new BufferedReader( new FileReader(filePath));
String strLine = "";
StringTokenizer str = null;

while( (strLine = br.readLine()) != null){
str = new StringTokenizer(strLine, ",");

while(str.hasMoreTokens())
csvValues.add(str.nextToken());
}

}catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
}
}

My csv file is something like this one:

1001,Name1,9
1005,Name2,20
1007,Name3,14

And I need it to be:

1001,Name1,9
1007,Name3,14
1005,Name2,20
Kominops
  • 3
  • 2

1 Answers1

3

Here is a Java 8 solution using streams with lambda syntax.

String filePath = "Filepath";
String content = Files.lines(Path.of(filePath))
                      .sorted(Comparator.comparing(line -> Integer.parseInt(line.split(",")[2])))
                      .collect(Collectors.joining("\n"));
Files.write(Paths.get("OutputFilepath"), content.getBytes());
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Arnaud B
  • 66
  • 3