【问题标题】:How do I copy objects from a ArrayList and order them by int size in a HashMap?如何从 ArrayList 复制对象并在 HashMap 中按 int 大小对它们进行排序?
【发布时间】:2019-10-20 04:31:58
【问题描述】:

所以我需要制作一个排行榜,它的位置取决于客户拥有的积分数量。

这是客户,

public Client(String username, String password, String phoneNumber, String nickname, Integer score) {

        super(username, password);

        this.phoneNumber = phoneNumber;

        this.nickname = nickname;

        this.score = score;

}

Clients 存储在 Clients ArrayList 中,对于排行榜,只需要显示“昵称”和“分数”,按照分数从大到小排序。有人建议我使用 HashMap,但由于我是 java 新手,所以我以前从未尝试过。

抱歉我的英语不好,感谢您的帮助:D 请说出你必须说的话,因为我对此很陌生,对事情的运作方式不太了解,任何提示都很好:)

【问题讨论】:

    标签: java arraylist hashmap


    【解决方案1】:

    由于您已经在使用ArrayList,并且您需要使用自定义逻辑订购list,您需要提供Comparator 以在Clients 之间进行比较:

    下面是一个例子:

    // 定义一个比较器类。

    class SortbyScore implements Comparator<Client> 
    { 
        // Used for sorting in descending order(bigger to smaller) of  score
        public int compare(Client a, Client b) 
        { 
            return b.score - a.score; 
            // if you want ascending order (smaller to bigger)
            // return a.score - b.score; 
        } 
    }
    
    
    ....
    // in your main method.. 
    List<Client> clientList = new ArrayList<>();
    ...
    /// insert data into clientList.
    
    // sort client list;
    Collections.sort(clientList , new SortbyScore());
    
    // now client list will contain the sorted data.
    System.out.println("Sorted: " clientList);
    // Better use for-loop and print each element.
    

    不知道为什么建议你使用 HashMap。

    查看此链接了解更多信息:How to Sort in Java

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-05
      • 1970-01-01
      • 2011-09-20
      • 2021-03-24
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      相关资源
      最近更新 更多