I have an arraylist filled with integers. I just need a way to get the top three integers in the arraylist.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With