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?
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);
}
}
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());
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