Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sort numbers in text file

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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))));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading