Redrield
Redrield

Reputation: 329

How to sort TreeMap with descending keys?

So what I'm trying to do right now for a school project is make a small high score system using external files, and using a TreeMap to map the name of the person to their score. However just based off of the nature of the way I'm iterating through it, the numbers are fragmented, I want to make it so that they go in descending order, but I'm not sure how. Any help would be appreciated! Thanks!

    File dir = new File(System.getProperty("user.dir") + "/saves");
    try {
        TreeMap<String, Character> scores2 = new TreeMap<>();
        for (File file : dir.listFiles()) {
            InputStream in = new FileInputStream(file);
            String name = file.getName().replace(".dat", "");
            int content;
            while((content = in.read())!=-1) {
                char num = (char)content;
                scores2.put(name, num);
            }
        }
        Text top5 = new Text();
        for (int i = 0; i < dir.list().length; i++) {
            Map.Entry<String, Character> currentEntry = scores2.pollFirstEntry();
            String name = currentEntry.getKey();
            Character score = currentEntry.getValue();
            top5.setText(top5.getText() + name + ": " + score + "\n");
        }
        newPane.setAlignment(Pos.CENTER);
        newPane.add(top5, 1, 1);
        Button exit = new Button("Arrière");
        exit.setOnMouseClicked(mEv -> scene.setRoot(pane));
        newPane.add(exit, 1, 3);
        scene.setRoot(newPane);
    }catch(NullPointerException | IOException e) {
        e.printStackTrace();
        Text txt = new Text("Il n'y a pas de scores pour montrer.");
        Button returnButto = new Button("Retourner?");
        GridPane errPane = new GridPane();
        errPane.add(txt, 1, 1);
        errPane.add(returnButto, 1, 2);
        errPane.setAlignment(Pos.CENTER);
        scene.setRoot(errPane);
        returnButto.setOnMouseClicked(mcEv -> scene.setRoot(pane));
    }

Upvotes: 0

Views: 7309

Answers (3)

joel314
joel314

Reputation: 1080

If you're using Java 8, you could proceed like this to sort by scores:

    Map<String, Character> scores2 = new TreeMap<>();
    scores2.put("Alice", 'C');
    scores2.put("Bob", 'E');
    scores2.put("Charlie", 'A');
    scores2.put("Dan", 'C');
    scores2.put("Eddie", 'B'); // Just an example
    System.out.println(scores2);

    Map<Character, List<String>> z = scores2.keySet().stream().collect(Collectors.groupingBy(k->scores2.get(k)));
    System.out.println(z);

It will first print your scores2, sorted by name:

{Alice=C, Bob=E, Charlie=A, Dan=C, Eddie=B}

The the second map, sorted by scores:

{A=[Charlie], B=[Eddie], C=[Dan, Alice], E=[Bob]}

Upvotes: 0

Vikrant Kashyap
Vikrant Kashyap

Reputation: 6846

use descendingKeyIterator function to Iterate through each key in reverse Order java.util.Iterator<K> descendingKeyIterator();

because TreeMap Stored data in default Natural Sorting Order. and Function descendingKeyIterator() will Iterate in reverse.

Thanks.

Upvotes: 0

JChrist
JChrist

Reputation: 1752

As mentioned in the java docs, the TreeMap:

is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

So, you will need to create your own Comparator, that sorts elements on descending order and pass that to the respective TreeMap constructor.

Upvotes: 3

Related Questions