2017-04-16 34 views
0

我使用HashMap<String,Integer>作为一种定时投票系统。其中字符串是对象的名称,整数是对象具有的投票数量。我试图做的是排序整数递减,如果他们是一个领带,我想选择谁以前没有赢得投票(如果他们中的任何一个)如何在Java中对HashMap进行排序?

我试过用TreeMap ,但它似乎没有做我想做的事情,因为它根据键的值排序,而我需要排序的值。也有些时候,两个对象都可能具有相同数量的投票,因此不起作用。

+2

你可以把你的代码, –

+0

您可以使用您designfor TIS例如一个简单的排序algorythm的例子,但如果你把一些你的代码是有帮助的 –

+0

@ maytham-ɯɐɥʇʎɐɯ我不认为这是重复的,因为破门者的要求 –

回答

0

here两者,这里是你如何排序Map其价值(按降序排列)与JDK 8:

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} 
+0

这是很好的价值以相反的顺序排序,但怎么打破领带? –

+0

@FedericoPeraltaSchaffner对于一个轮胎,我不太明白OP的意思,如果他们以前赢得了投票或没有。有没有存储信息的变量?如果OP能够澄清,那么我可以编辑我的答案。 –

+0

我的理解是,即如果有3票保罗和2票赞成安,并且安被投票,那么安需要在保罗之前出现在排序中,因为保罗以前就是投票的人。也许@ ctooley17可以澄清这... –

0

为了能够确定结果,你需要的不仅仅是一个整数。一种解决方案可能是创建一个自定义对象,该对象包含额外信息并实现可比较的(类似于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); 
相关问题