Getting top 3 highest values in arraylist?

17,866

Solution 1

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 view on the base list, so changes made there would be reflected in top3.

Solution 2

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.

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

Solution 3

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).

Share:
17,866
Cody Thompson
Author by

Cody Thompson

Updated on July 02, 2022

Comments

  • Cody Thompson
    Cody Thompson almost 2 years

    I have an arraylist filled with integers. I just need a way to get the top three integers in the arraylist.