我需要 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.votespareTo(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.