Java实践题:投票选举,三种票5分,3分,2分
投票选举,每个人三张票,投给不同的人,统计每个人的分数,然后输出前三名,如果分数相同,根据名字正序排序
首先有一个实体类:
@Data
public class Vote {
private String Five;
private String Three;
private String Two;
public Vote(String five, String three, String two) {
Five = five;
Three = three;
Two = two;
}
}
我们首先创建一个类,进行接收每个人以及得到的分数:
@Data
public class VoteVo {
private String username;
private int score;
public VoteVo(String username, Integer score) {
this.username = username;
this.score = score;
}
}
然后方法如下:
public List<String> getNamesSort(List<Vote> list) {
List<VoteVo> voteVos = new ArrayList<>();
HashMap<String, Integer> map = new HashMap<>();
for(Vote vote:list){
if(map.containsKey(vote.getFive())){
map.put(vote.getFive(),map.get(vote.getFive())+5);
}else {
map.put(vote.getFive(),5);
}
if(map.containsKey(vote.getThree())){
map.put(vote.getThree(),map.get(vote.getThree())+3);
}else {
map.put(vote.getThree(),3);
}
if(map.containsKey(vote.getTwo())){
map.put(vote.getTwo(),map.get(vote.getTwo())+2);
}else {
map.put(vote.getTwo(),2);
}
}
map.forEach((key,value)->{
VoteVo voteVo = new VoteVo(key, value);
voteVos.add(voteVo);
});
Collections.sort(voteVos, new Comparator<VoteVo>() {
@Override
public int compare(VoteVo o1, VoteVo o2) {
if(o1.getScore()!= o2.getScore()){
return Integer.compare(o2.getScore(),o1.getScore());
}else {
return o1.getUsername().compareTo(o2.getUsername());
}
}
});
List<String> names=new ArrayList<>();
for(int i=0;i<3;i++){
names.add(voteVos.get(i).getUsername());
}
return names;
}
总结,这样就实现了,我们需要的业务,找到了投票选举得分前三的人的名字。