TopItems { public static List<GenericUserSimilarity.UserUserSimilarity> getTopUserUserSimilarities( int howMany, Iterator<GenericUserSimilarity.UserUserSimilarity> allSimilarities) { Queue<GenericUserSimilarity.UserUserSimilarity> topSimilarities = new PriorityQueue<>(howMany + 1, Collections.reverseOrder()); boolean full = false; double lowestTopValue = Double.NEGATIVE_INFINITY; while (allSimilarities.hasNext()) { GenericUserSimilarity.UserUserSimilarity similarity = allSimilarities.next(); double value = similarity.getValue(); if (!Double.isNaN(value) && (!full || value > lowestTopValue)) { topSimilarities.add(similarity); if (full) { topSimilarities.poll(); } else if (topSimilarities.size() > howMany) { full = true; topSimilarities.poll(); } lowestTopValue = topSimilarities.peek().getValue(); } } int size = topSimilarities.size(); if (size == 0) { return Collections.emptyList(); } List<GenericUserSimilarity.UserUserSimilarity> result = new ArrayList<>(size); result.addAll(topSimilarities); Collections.sort(result); return result; } private  TopItems(); static List<RecommendedItem> getTopItems(int howMany,
                                                  LongPrimitiveIterator possibleItemIDs,
                                                  IDRescorer rescorer,
                                                  Estimator<Long> estimator); static long[] getTopUsers(int howMany,
                                   LongPrimitiveIterator allUserIDs,
                                   IDRescorer rescorer,
                                   Estimator<Long> estimator); static List<GenericItemSimilarity.ItemItemSimilarity> getTopItemItemSimilarities(
    int howMany, Iterator<GenericItemSimilarity.ItemItemSimilarity> allSimilarities); static List<GenericUserSimilarity.UserUserSimilarity> getTopUserUserSimilarities(
    int howMany, Iterator<GenericUserSimilarity.UserUserSimilarity> allSimilarities);  }
@Test public void testTopUserUser() throws Exception { List<GenericUserSimilarity.UserUserSimilarity> sims = Lists.newArrayList(); for (int i = 0; i < 99; i++) { sims.add(new GenericUserSimilarity.UserUserSimilarity(i, i + 1, i / 99.0)); } List<GenericUserSimilarity.UserUserSimilarity> res = TopItems.getTopUserUserSimilarities(10, sims.iterator()); int gold = 99; for (GenericUserSimilarity.UserUserSimilarity re : res) { assertEquals(gold--, re.getUserID2()); } }
@Test public void testTopUserUserAlt() throws Exception { List<GenericUserSimilarity.UserUserSimilarity> sims = Lists.newArrayList(); for (int i = 0; i < 99; i++) { sims.add(new GenericUserSimilarity.UserUserSimilarity(i, i + 1, 1 - (i / 99.0))); } List<GenericUserSimilarity.UserUserSimilarity> res = TopItems.getTopUserUserSimilarities(10, sims.iterator()); int gold = 0; for (GenericUserSimilarity.UserUserSimilarity re : res) { assertEquals(gold++, re.getUserID1()); } }