Sorting Objects By Int

Discussion in 'Plugin Development' started by r0306, May 9, 2013.

Thread Status:
Not open for further replies.
  1. Offline

    r0306

    I have a List of a custom Object with an integer that keeps track of the score. How would I go about sorting this list so that they are placed with the scores going from greatest to least?
     
  2. Offline

    socram8888

  3. Offline

    r0306

    socram8888
    Can I have an example of how I would do this when comparing objects?
     
  4. Offline

    socram8888

    Code:
    TreeMap<Integer, HighScore> highscores = new TreeMap<Integer, HighScore>();
    highscores.put(1920, new HighScore("PlayerA", 1920));
    highscores.put(2032, new HighScore("PlayerB", 2032));
    
    // by default SortedMaps use natural (ie low to high ordering), so we have to use the desdendingIterator method
    Iterator<HighScore> it = highscores.descendingIterator();
    int scorecount = 1;
    while (it.hasNext()) {
    HighScore highscore = it.next();
    System.out.println("Score #" + scorecount + ": " + highscore.getPlayer() + " with " + highscore.getScore() + " points");
    scorecount++;
    };
    
    
    You can also use a TreeSet if HighScore implements Comparable, which is the function used to order the Map contents.
     
Thread Status:
Not open for further replies.

Share This Page