skip to Main Content

I want to make a leaderboard with SQL.
So I have to ORDER BY with kills in my case to get the results sorted.

But with the result set, the order is wrong.

HashMap<String, Integer> player_list = new HashMap<>();
preparedStatement = this.pvpBox.getDtb().getConnection().prepareStatement(
    "SELECT player_name, kills FROM players ORDER BY kills DESC LIMIT 10");
ResultSet resultSet = preparedStatement.executeQuery();

while (resultSet.next()) {
    player_list.put(resultSet.getString("player_name"), resultSet.getInt("kills"));
}

No error message.

I’ve already tried in the “SQL” section of PHPMyAdmin and I’m getting the expected result..

Table example :

    player_name     kills
    player1         40
    player2         20
    player3         50
    player4         10
    player5         30

Actual result :

    player_name     kills
    player5         30
    player1         40
    player4         10
    player2         20
    player3         50

Expected result :

    player_name     kills
    player3         50
    player1         40
    player5         30
    player2         20
    player4         10

I’m using Java 8 and Apache 2.

Solution : Use the LinkedHashMap instead of HashMap (hashmap does not have any order).

3

Answers


  1. That player_list you are using is quite obviously not a List. With the put() method and two arguments, it looks like a Map.

    If what you use is a HashMap, no wonder the order is arbitrary – HashMap does not retain any kind of ordering.

    You might want a LinkedHashMap, or another data structure altogether, like a custom object that you then actually store in a list, not in a map.

    Login or Signup to reply.
  2. I think the problem is with the player_list which is a non-sorted map implementation. If you want to preserve the order of inserts in the map, use LinkedHashMap.

    Login or Signup to reply.
  3. Is player_list a hashmap object? Hashmap does’nt maintain the order of the values inserted.Instead try using LinkedHashMap or TreeMap.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search