0

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));
    }
Grzegorz Piwowarek
  • 13,172
  • 8
  • 62
  • 93
Redrield
  • 309
  • 1
  • 5
  • 15
  • 1
    A `TreeMap` keeps its entries sorted by key. The key here is the person's name (the first parameter to `put`), not the score. So your tree will be sorted by name. That doesn't seem like what you want. – ajb Apr 26 '16 at 05:23
  • http://stackoverflow.com/questions/18923167/sorting-descending-order-java-map – Praveen Kumar Apr 26 '16 at 05:24
  • Possible duplicate of [Sorting custom data structure on Key in TreeMap](http://stackoverflow.com/questions/7385189/sorting-custom-data-structure-on-key-in-treemap) – T D Nguyen Apr 26 '16 at 05:26
  • Alright, so I changed the mapping system to TreeMap, but now my problem is that on a duplicate score one of the people who had the score collision will have a blank space as their key, I also tried TreeMap> But that didn't work either :/ – Redrield Apr 26 '16 at 13:29

3 Answers3

3

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.

JChrist
  • 1,734
  • 17
  • 23
  • Still no good. The `Comparator` gives you a way to sort the keys. The keys in the above code are `Strings`. So he could sort those in descending order, but that just means that the person named Zywicki will be at the top of the list. – ajb Apr 26 '16 at 05:25
  • 1
    @ajb But that's just the OP's problem. He's mixing up the keys and values. They should be the other way around, since he's using the map *only* for the ordering. – Kayaman Apr 26 '16 at 06:13
0

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.

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
0

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]}
joel314
  • 1,060
  • 1
  • 8
  • 22