简体   繁体   English

Java:以百分比表示的高分列表

[英]Java: Kind of list for highscore in percent

I want to create a list that holds a value and a name. 我想创建一个包含值和名称的列表。 The value is the percentage a player got in two decimals (for instance 0.94) and the name is simply the player's name. 该值是玩家获得的两位小数百分比(例如0.94),而名称只是玩家的名称。

I have this list: 我有这个清单:

List<Highscore> highscore = new LinkedList<Highscore>(Arrays.asList());

Highscore contains: Highscore包含:

String percent;
String name;

What is the best way to sort this list so the highest percentage is first and so forth. 排序此列表的最佳方法是什么,因此百分比最高的是第一个,依此类推。 I've seen some Comparator methods, but I did not understand them at all and they did not work for me. 我已经看过一些Comparator方法,但是我根本不理解它们,它们对我也不起作用。 For instance: 例如:

if (highscore.size() > 0) {
    Collections.sort(highscore.size, new Comparator<Campaign>() {
        @Override
        public int compare(final Campaign object1, final Campaign object2) {
            return object1.getName().compareTo(object2.getName());
        }
       } );
   }

Store them in a TreeSet and make the object Comparable with the high score being used to compare first and then name second. 将它们存储在TreeSet ,并使对象Comparable最高的对象Comparable ,然后首先进行比较,然后命名。 (Or use a custom Comparator on the TreeSet that does the same thing). (或在执行相同操作的TreeSet上使用自定义Comparator器)。 That will have them in a permanently sorted collection. 这将使它们处于永久排序的集合中。

Otherwise your example is correct except for the Comparator you are using which looks at name not score. 否则,您的示例是正确的,除了您使用的Comparator (名称不是得分)。

Storing the percentage as an integer (or float) rather than a String will make this easier. 将百分比存储为整数(或浮点数)而不是String可以简化此过程。

Whatever you do you need a Comparator looking something like: 无论您做什么,都需要一个类似以下内容的Comparator

new Comparator<Campaign>() {
    @Override
    public int compare(final Campaign object1, final Campaign object2) {
        int result = //Compare your scores here - however you store them will change this bit
        if (result != 0) {
             return result;
        }
        // If scores are equal then just return the result of a comparison by name
        return object1.getName().compareTo(object2.getName());
    }
}

The name comparison is needed as otherwise two people with the same score only one would appear in the Set . 需要进行名称比较,否则两个具有相同分数的人只会在Set出现一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM