如何使用集合从arrayList调用第二大数字 [英] How can I call second largest number from arrayList using collections

查看:86
本文介绍了如何使用集合从arrayList调用第二大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的阵列"列表数据中的最高,第二高和第三高的数字.我通过使用Collections.max()获得最大价值(最高数字).但是,我需要第二大和第三大值.
我的代码:

I need Highest,second highest and third highest number from My Array list Data. I am getting Max Value (highest number) by using Collections.max(). But, I need Second largest and third largest values.
My Code:

maxPartyid = 
Collections.max(electionresdashlist.get(k).getPartyNamesDTO());  //1st Highest
						 
System.out.println( "maxPartyid:::"+maxPartyid);
             
in DTO :
public class PartyNamesDTO implements Comparable<PartyNamesDTO>{

	private String partyId;
	public String getPartyId() {
		return partyId;
	}
	public void setPartyId(String partyId) {
		this.partyId = partyId;
	}
	private Integer votes;
	
	
	public Integer getVotes() {
		return votes;
	}
	public void setVotes(Integer votes) {
		this.votes = votes;
	}
	
	@Override
        public int compareTo(PartyNamesDTO emp) {
            return this.votes.compareTo(emp.getVotes());
        }
	
        public String toString(){
            return partyId;
        }
}        
             
             

推荐答案

由于您已经在PartyNamesDTO上实现了Comparable接口,因此您可以

Since you implemented the Comparable interface on PartyNamesDTO you can just do

Collections.sort(electionresdashlist)

这将使您的列表根据compareTo逻辑进行排序,如果您的排序是升序,则可以获得最大记录为

which will make your list sorted according to compareTo logic and if your sorting is ascending order then you can get max record as

electionresdashlist.get(electionresdashlist.size()-1);
electionresdashlist.get(electionresdashlist.size()-2);
electionresdashlist.get(electionresdashlist.size()-3);

,如果是降序排列,则相反.

and if it is descending order the other way around

这篇关于如何使用集合从arrayList调用第二大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆