我正在使用一种HashMap<String,Integer>
定时投票系统。其中字符串是对象的名称,整数是该对象拥有的投票数量。我想要做的是将整数降序排序,如果他们是平局,我想选择以前没有赢得投票的人(如果他们中的任何一个赢得了选票)
我尝试使用 a TreeMap
,但它似乎没有做我想要的,因为它根据键的值进行排序,而我需要对值进行排序。也不起作用,因为有时两个对象可能都有相同的投票数。
为了能够确定平局的结果,您需要的不仅仅是一个整数。一种解决方案可能是创建一个自定义对象,该对象包含额外信息并实现可比性(类似于 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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句