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: