2

I'm working on a leaderboard and my data is stored in an ArrayList as

int + " " + username

I've been trying to sort it to display.

public static void main (String[] args) throws java.lang.Exception
{

    List<String> leaderboard = new ArrayList<String>();

    leaderboard.add("11 John");
    leaderboard.add("23 annie");
    leaderboard.add("1 putin");
    leaderboard.add("101 king");
    Collections.sort(leaderboard);

    for(int i = 0; i < leaderboard.size(); i++) {   
        System.out.print(leaderboard.get(i));
        System.out.println();
    } 

}

Outputs an alphabetical sort:

1 putin
101 king
11 John
23 annie

when I need

1 putin
11 John
23 annie
101 king

and to finish it off I would use

Collections.reverse(leaderboard);

To display it as a high score chart.

2
  • Make custom objects with a number and name as instance attributes. Commented Jan 2, 2016 at 22:21
  • Why throws java.lang.Exception? Commented Jan 2, 2016 at 22:52

1 Answer 1

4

You could create a custom Comparator to treat the first part of the string numerically:

public class NumericalStringComparator implements Comparator<String> {
    @Override
    public int compare (String s1, String s2) {
        int i1 = Integer.parseInt(s1.split(" ")[0]);
        int i2 = Integer.parseInt(s2.split(" ")[0]);
        int cmp = Integer.compare(i1, i2);
        if (cmp != 0) {
            return cmp;
        }
        return s1.compareTo(s2);
    }
}

You could then use it to in a reversed order to sort your collection:

 Collections.sort(leaderboard, new NumericalStringComparator().reversed());
Sign up to request clarification or add additional context in comments.

2 Comments

Wow that was fast. Works flawlessly thanks a lot! Using his code I get the proper sort. Thanks. Will accept as answer after 5 minute cooldown. Appreciate it.
This is only if you need the data to be stored as Strings. You probably don't. The recommended solution is to either use a Map<String, Integer> (instead of the current List) to map names to their respective scores; or to create a custom object that effectivelly does the same "key-value" pairing. This is to avoid storing numbers as String (memory-inefficient) and having to parse them in/out of Strings (cpu-inefficient)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.