[英]How to sort a HashMap in Java?
我將HashMap<String,Integer>
用於某種定時投票系統。 其中,字符串是對象的名稱,整數是對象擁有的票數。 我想做的是對整數降序進行排序,如果它們是平局,我想選擇一個以前沒有贏得選票的人(如果他們中的任何一個贏得選票)
我嘗試使用TreeMap
,但是它似乎並沒有滿足我的要求,因為它根據鍵的值進行排序,而我需要對值進行排序。 有時兩個對象可能具有相同的投票數,因此也不起作用。
從這里開始 ,這是如何使用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}
為了確定平局的結果,您將需要的不僅僅是整數。 一種解決方案是創建一個自定義對象,該對象可以保存額外的信息並實現可比較的功能(類似於Walter所說的)。
從我的帖子中可以看出,當有共同投票時,您希望結果是尚未像其他共同投票權一樣被選擇的期權。 如果是這種情況,則下面的解決方案(使用日期作為次要信息)應該可以使用。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.