Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting top 3 highest values in arraylist? [closed]

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

like image 567
Cody Thompson Avatar asked Jul 09 '13 04:07

Cody Thompson


2 Answers

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.

like image 134
Bohemian Avatar answered Sep 19 '22 07:09

Bohemian


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

like image 45
Rahul Avatar answered Sep 20 '22 07:09

Rahul