I am trying to simulate a game board where multiple players can submit their game scores.
The POJO viz. Entry.java represents an entry in the leaderboard. Note the overriden equals() method.
Position is the position in the leaderboard, 1 being the user with the highest score
public class EntryTreeMapOption {
private String uid;
private int score;
private int position;
public EntryTreeMapOption(String uid, int score) {
this.uid = uid;
this.score = score;
}
public EntryTreeMapOption() {
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uid == null) ? 0 : uid.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EntryTreeMapOption other = (EntryTreeMapOption) obj;
if (uid == null) {
if (other.uid != null)
return false;
} else if (!uid.equals(other.uid))
return false;
return true;
}
@Override
public String toString() {
return "Entry [uid=" + uid + ", score=" + score + ", position=" + position + "]";
}}
I am using a TreeMap to store the entries, based on the score, they are sorted automatically
public class GameDefault2 {
private TreeMap<EntryMapOption, String> leaderBoardEntryUserMap;
{
leaderBoardEntryUserMap = new TreeMap<>(Comparator.comparingInt(EntryTreeMapOption::getScore).reversed()
.thenComparing(EntryTreeMapOption::getUid));
}
@Override
public void submitScore(String uid, int score) {
EntryMapOption newEntry = new EntryMapOption(uid, score);
leaderBoardEntryUserMap.put(newEntry, uid);
}
@Override
public List<EntryMapOption> getLeaderBoard(String uid) {
List<EntryMapOption> userEntryList = .....
.....
.....
return entriesOptionTwo;
}
}
How do I set the 'position' field of an Entry ? e.g: Below are entries sorted as per the scores, how do I get the corresponding 'index/position' and set it in the entry ?
Entry [uid=user1, score=14, position=0]
Entry [uid=user2, score=8, position=0]
Entry [uid=user3, score=7, position=0]
Entry [uid=user4, score=7, position=0]
Entry [uid=user5, score=4, position=0]
Entry [uid=user6, score=3, position=0]
Entry [uid=user7, score=3, position=0]
Entry [uid=user8, score=1, position=0]
Now, user1 entry should have position=1, user2 entry should have position=2 and so on.