VectorHelper { public static List<Pair<Integer, Double>> topEntries(Vector vector, int maxEntries) { int sizeOfNonZeroElementsInVector = Iterables.size(vector.nonZeroes()); if (sizeOfNonZeroElementsInVector < maxEntries) { maxEntries = sizeOfNonZeroElementsInVector; } PriorityQueue<Pair<Integer, Double>> queue = new TDoublePQ<Integer>(-1, maxEntries); for (Element e : vector.nonZeroes()) { queue.insertWithOverflow(Pair.of(e.index(), e.get())); } List<Pair<Integer, Double>> entries = Lists.newArrayList(); Pair<Integer, Double> pair; while ((pair = queue.pop()) != null) { if (pair.getFirst() > -1) { entries.add(pair); } } Collections.sort(entries, new Comparator<Pair<Integer, Double>>() { @Override public int compare(Pair<Integer, Double> a, Pair<Integer, Double> b) { return b.getSecond().compareTo(a.getSecond()); } }); return entries; } private  VectorHelper(); static String vectorToCSVString(Vector vector, boolean namesAsComments); static String buildJson(Iterable<Pair<String, Double>> iterable); static String buildJson(Iterable<Pair<String, Double>> iterable, StringBuilder bldr); static List<Pair<Integer, Double>> topEntries(Vector vector, int maxEntries); static List<Pair<Integer, Double>> firstEntries(Vector vector, int maxEntries); static List<Pair<String, Double>> toWeightedTerms(Collection<Pair<Integer, Double>> entries,
                                                           final String[] dictionary); static String vectorToJson(Vector vector, String[] dictionary, int maxEntries, boolean sort); static void vectorToCSVString(Vector vector,
                                       boolean namesAsComments,
                                       Appendable bldr); static String[] loadTermDictionary(File dictFile); static String[] loadTermDictionary(Configuration conf, String filePattern);  }
@Test public void testTopEntries() throws Exception { Vector v = new SequentialAccessSparseVector(10); v.set(2, 3.1); v.set(4, 1.0); v.set(6, 8.1); v.set(7, -100); v.set(9, 12.2); v.set(1, 0.0); v.set(3, 0.0); v.set(8, 2.7); assertEquals(6, VectorHelper.topEntries(v, 6).size()); assertTrue(VectorHelper.topEntries(v, 9).size() < 9); assertTrue(VectorHelper.topEntries(v, 5).size() < Iterables.size(v.nonZeroes())); }
@Test public void testTopEntriesWhenAllZeros() throws Exception { Vector v = new SequentialAccessSparseVector(10); v.set(2, 0.0); v.set(4, 0.0); v.set(6, 0.0); v.set(7, 0); v.set(9, 0.0); v.set(1, 0.0); v.set(3, 0.0); v.set(8, 0.0); assertEquals(0, VectorHelper.topEntries(v, 6).size()); }