What would be the best solution to find top N (say 10) elements in an unordered list (of say 100).
The solution which came in my head was to 1. sort it using quick s
You can use List
and can guava's Comparators
class to get the desired results. It is a highly optimized solution. Please see a sample below, which gets top 5 numbers. Api can be found here.
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collector;
import org.junit.Test;
import com.google.common.collect.Comparators;
import com.google.common.collect.Lists;
public class TestComparator {
@Test
public void testTopN() {
final List numbers = Lists.newArrayList(1, 3, 8, 2, 6, 4, 7, 5, 9, 0);
final Collector> collector = Comparators.greatest(5,
Comparator.naturalOrder());
final List top = numbers.stream().collect(collector);
System.out.println(top);
}
}
Output: [9, 8, 7, 6, 5]