Find top N elements in an Array

前端 未结 12 1234
南笙
南笙 2020-11-28 06:18

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

12条回答
  •  感情败类
    2020-11-28 06:46

    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]

提交回复
热议问题