如何用Java对HashMap进行排序?

时间:2017-04-16 00:27:33

标签: java hashmap bukkit

我使用HashMap<String,Integer>作为一种定时投票系统。其中字符串是对象的名称,整数是对象具有的投票数。我试图做的是将整数降序排序,如果它们是平局,我想选择之前没有赢得投票的人(如果他们中的任何一个都这样做了)

我尝试使用TreeMap,但它似乎没有做我想要的,因为它根据键的值进行排序,而我需要将值排序。也不起作用,因为有时候两个对象都可以拥有相同的票数。

2 个答案:

答案 0 :(得分:0)

here获取,以下是使用JDK 8对Map的值进行排序(按降序排列)的方法:

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet().stream().sorted(Map.Entry.comparingByValue(Collections.reverseOrder())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}

示例:

Map<String, Integer> votes = new HashMap<>();

votes.put("A", 5);
votes.put("B", 17);
votes.put("C", 1);

System.out.println(votes);

>> {A=5, B=17, C=1}

votes = sortByValue(votes);

System.out.println(votes);

>> {B=17, A=5, C=1}

答案 1 :(得分:0)

为了能够确定平局的结果,您需要的不仅仅是整数。一种解决方案可能是创建一个自定义对象,其中包含额外的信息并实现可比较的(类似于Walter所说的)。

从我的帖子中可以看出,当投票结果相同时,您希望结果是最近未被选中的选项。如果是这种情况,则下面的解决方案(使用Date作为辅助信息)应该可以正常工作。

import java.util.Date;

public class VoteOption implements Comparable<VoteOption>{

    private String name;
    private Integer votes;
    private Date lastVote;

    /** Constructor */
    public VoteOption(String name){
        this.name = name;
        this.lastVote = new Date();
        this.votes = 0;
    }

    /** gets the name of this option */
    public String name(){
        return this.name;
    }

    /** gets the number of votes this option currently has */
    public int votes(){
        return this.votes;
    }

    /** Call this method if the vote passed with this option.
     * It will update the lastVote date so that this will become the
     * last option to be picked if there is a tie in the next vote. */
    public void votePassed(){
        this.lastVote = new Date();
    }

    /** resets the vote count back to 0 */
    public void resetVoteCount(){
        this.votes = 0;
    }

    /** Adds 1 vote to the vote count */
    public void vote(){
        this.votes ++;
    }

    @Override
    public int compareTo(VoteOption otherOption){
        int compareVotes = this.votes.compareTo(otherOption.votes);
        if(compareVotes!=0){
            return compareVotes;
        } else {
            //handle vote ties
            int compareDates = this.lastVote.compareTo(otherOption.lastVote);
            return compareDates;
        }
    }
}

要对这些选项的列表进行排序,您应该调用

Collections.sort(list);
相关问题