Home > OS >  Take records from set and count how many records for each player id
Take records from set and count how many records for each player id

Time:05-22

I'm making a leaderboard in my game and I have tiles with certain player ids assigned to them.

I need to take the following data (which is a set containing my 'Tile' records):

    [Tile[id=eeebeaa4e03c8910e5c17925439f1fa1abb,position=Vec[x=-11.0, y=6.0, z=73.0], player_id=1oyr8l], Tile[id=3c10969e83a61f44139d5dbeb8b41c9e,position=Vec[x=-12.0, y=6.0, z=73.0], player_id=1oyr8l], Tile[id=f51fd6f3eb407305a49bde1cb2cf44fe,position=Vec[x=-12.0, y=6.0, z=74.0], player_id=qX9Bh7]]

I want to format it into something like:

    1oyr8l: 2
    qX9Bh7: 1

Or in code form:

    public record Tile(String id, Vec position, String owner) {
    // irrelevant code here
    }

    private final Set<Tile> userTiles = getTiles() // dummy func but you get the idea

I want to take userTiles, which is a Set<Tile> and make it into the sorted & counted format I showed above in text format, but in the form of a HashMap, such as:

    HashMap<String,Integer> leaderboard = new HashMap<String,Integer>();

CodePudding user response:

Iterate over your Tiles. for(Tile t : getTiles())

Extract the player ID. String playerId = t.player_id()

Check if the player ID exists in the HashMap. if leaderboard.containsKey(playerId)

If it does, increment the value for that key.

If not, add the map with a value of 1.

  • Related