java - 从 treeMap 中删除最小的键

标签 java android algorithm treemap scoring

我正在使用 treeMap 创建一个评分系统,我只想显示前 3 个结果。
当玩家输入第4个结果时(如果它大于当前最小值)我如何让它删除最小值并用新值替换它。

到目前为止,我的代码对分数进行了排序:

 Map<Integer, String> treeMap = new TreeMap<Integer, String>(new MyCopr());
    treeMap.put(name1val, name1);
    treeMap.put(name2val, name2);
    treeMap.put(name3val, name3);
    treeMap.put(tempval, tempname);

    for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
        playername1.append("Key : " + entry.getKey() + " Value : "
                + entry.getValue() + "\n");
    }
}

class MyCopr implements Comparator<Integer> {
    @Override
    public int compare(Integer lhs, Integer rhs) {
        return rhs.compareTo(lhs);
    }
}

从这里我可以做些什么来替换最小值?谢谢。

最佳答案

我会使用一组分数(像这样)-

private static int MAX_SCORES = 3;
private SortedSet<Score> scores = new TreeSet<Score>();

public Set<Score> getScores() {
  return scores;
}

public void addScore(String name, int score) {
  scores.add(new Score(name, score));
  while (scores.size() > MAX_SCORES) {
    scores.remove(scores.first());
  }
}

private class Score implements Comparable<Score> {
  private String name;
  private int score;

  private Score(String name, int score) {
    this.name = name;
    this.score = score;
  }

  public int compareTo(Score obj) {
    if (this == obj) {
      return 0;
    }
    if (this.score < obj.score) {
      return -1;
    } else if (this.score > obj.score) {
      return 1;
    }
    return name.compareTo(obj.name);
  }

  public String toString() {
    return name + " - score = " + score;
  }
}

然后像这样使用它......

System.out.println(obj.getScores());
obj.addScore("Player 1", 1);
obj.addScore("Player 2", 2);
obj.addScore("Player 3", 3);
System.out.println(obj.getScores());
obj.addScore("Player 4", 4);
System.out.println(obj.getScores());

这会产生这个(当我运行它时)-

[]
[Player 1 - score = 1, Player 2 - score = 2, Player 3 - score = 3]
[Player 2 - score = 2, Player 3 - score = 3, Player 4 - score = 4]

关于java - 从 treeMap 中删除最小的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20447879/

相关文章:

java - GZIPInputStream 的工作原理

java - 探索要打印的 Java 对象内容

java - 在 Rails 应用程序中实现 Java 门面/服务概念的最佳方式

android - 发送 JSON Post 请求到 Contact Form 7

android - 为什么我无法使用 google map V2

java - 为什么我的两个线程可以通过非 volatile 字段进行协调?

Android 11 (R) 在查询 ACTION_IMAGE_CAPTURE 的 Intent 时返回空列表

Java:如何根据提供的模式从 String 中提取值并将其填充到 Map 中?

c# - C# 中的 Char.IsHex()

algorithm - 哪种算法对于高维特征和小样本量表现更好?