如何使用集合从 arrayList 调用第二大数字 [英] How can I call second largest number from arrayList using collections
本文介绍了如何使用集合从 arrayList 调用第二大数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要 ArrayList
中的最高、第二高和第三高的数字.我通过调用 Collections.max()
获得最大值(即最高数字),但我还需要第二大和第三大的值.
我的代码:
I need highest, second highest and third highest numbers from my ArrayList
. I am getting max value (i.e. highest number) by calling Collections.max()
but I also need the second largest and the 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;
}
}
推荐答案
你可以使用java 8流来排序和跳过不必要的元素
You can use java 8 streams to sort and skip unnecessary elements
list.stream().sorted(Comparator.reverseOrder()).limit(2).skip(1).findFirst()
findFirst()
返回对象的 Optional
.
这篇关于如何使用集合从 arrayList 调用第二大数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文