Home > Software design >  How to sort numbers in text file
How to sort numbers in text file

Time:11-23

Hello everyone I have a text file for scores and I want to sort the numbers,not the text in the file but my code just sort the text.Please help me to fix this problem.
This is my score file in a.txt :

Cow:50
Bob:60
Van:70

This is my code:

public class highscore {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("src/a.txt"));
        ArrayList<String> str = new ArrayList<>();
        String line = "";
        while((line=reader.readLine())!=null){
            str.add(line);
        }
        reader.close();
        Collections.sort(str);
        FileWriter writer = new FileWriter("b.txt");
        for(String s: str){
            writer.write(s);
            writer.write("\r\n");
        }
        writer.close();
    }
}

CodePudding user response:

Sort the numbers in the text, which means you need to extract the numbers:

// descending
str.sort((o1, o2) -> Integer.compare(
            Integer.parseInt(o2.substring(o2.indexOf(":")   1)),
            Integer.parseInt(o1.substring(o1.indexOf(":")   1))));
// or ascending
str.sort(Comparator.comparingInt(o -> Integer.parseInt(o.substring(o.indexOf(":")   1))));
  • Related