最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

如何使用集合从 arrayList 调用第二大数字

SEO心得admin34浏览0评论
本文介绍了如何使用集合从 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.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.

发布评论

评论列表(0)

  1. 暂无评论