java 获取数组列表中的前 3 个最高值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17540251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting top 3 highest values in arraylist?
提问by Cody Thompson
I have an arraylist filled with integers. I just need a way to get the top three integers in the arraylist.
我有一个填充整数的数组列表。我只需要一种方法来获取数组列表中的前三个整数。
采纳答案by Bohemian
List<Integer> list;
Collections.sort(list);
List<Integer> top3 = new ArrayList<Integer>(list.subList(list.size() -3, list.size()));
I could have simply used the subList, but the list returned from subList() is a viewon the base list, so changes made there would be reflected in top3.
我可以简单地使用 subList,但是从 subList() 返回的列表是基本列表上的一个视图,因此在那里所做的更改将反映在 top3 中。
回答by Suresh Atta
Make use of List#subList(int fromIndex,int toIndex)
使用List#subList(int fromIndex,int toIndex)
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
返回此列表中指定的 fromIndex(包括)和 toIndex(不包括在内)之间的部分的视图。
yourList.subList(yourList.size() -n, yourList.size());
As per sublist docs
根据子列表文档
回答by andy256
It depends on the size of the list and what performance you want. If the list is "small" then any of the earlier solutions will suffice, depending on your requirements.
这取决于列表的大小和您想要的性能。如果列表“小”,那么根据您的要求,任何早期的解决方案就足够了。
If the list is "large" and performance is important, then you should iterate through the list and keep the 3 largest as you go.
如果列表“很大”并且性能很重要,那么您应该遍历列表并保持最大的 3 个。
Another trade-off is your time and bugs vs using libraries. An of the library approaches mentioned will work in less of your programmer-time than a custom-coded solution
另一个权衡是你的时间和错误与使用库。与自定义编码解决方案相比,所提到的一种库方法将在更少的程序员时间内起作用
回答by SudoRahul
You need to write your own comparator and use Collections.sort(list, comparator)
on your ArrayList
, which will bring the top 3 integers to the top(this is purely based on the logic in your comparator).
您需要编写自己的比较器并Collections.sort(list, comparator)
在您的 上使用ArrayList
,这会将前 3 个整数带到顶部(这纯粹是基于比较器中的逻辑)。
回答by oks16
use Collections.sort to sort and retrieve the first three values
使用 Collections.sort 对前三个值进行排序和检索
回答by Evgeniy Dorofeev
Put all the elements into a TreeSet
using TreeSet(Collection c)
constructor then use TreeSet.descendingIterator
to get the first 3 elements. A list may contain duplicates, using TreeSet guarantees that you retrieve 3 distinct largest values.
将所有元素放入TreeSet
usingTreeSet(Collection c)
构造函数中,然后使用TreeSet.descendingIterator
获取前 3 个元素。列表可能包含重复项,使用 TreeSet 保证您检索 3 个不同的最大值。