Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to keep 10 biggest integer while reading a list in java?

I have a list of integer in a list and want to keep the 10 biggest while I'm iterating over the list and keep them in a TreeSet. I'm using this code :

for(Integer i : list) {                
            if (treeSet.size() < 10) {                    
                treeSet.add(i);
            } else if (i > treeSet.last()) {
                treeSet.pollLast();
                treeSet.add(i);
            }
        }

but results is defferent when I change order of integers in list before running this code. Is my code true?

like image 416
user3070752 Avatar asked Apr 27 '26 07:04

user3070752


2 Answers

treeSet is holding its data in ascending order (first is the smallest), so you should be replacing first element, not last:

for(Integer i : list) {                
    if (treeSet.size() < 10) {                    
        treeSet.add(i);
    } else if (i > treeSet.first()) {
        treeSet.pollFirst();
        treeSet.add(i);
    }
}
like image 64
user3707125 Avatar answered Apr 28 '26 19:04

user3707125


Use Collection.sort() and get the desired number of results with List.subList().

// Sort the arraylist
Collections.sort(list); 
//gets the last 10 item, last is the largest for ascending default sort
list.subList(list.size()-10, list.size());
like image 20
Jordi Castilla Avatar answered Apr 28 '26 19:04

Jordi Castilla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!