Here you can find the source of selectTopN(List> originalList, int topN, Comparator
Parameter | Description |
---|---|
originalList | The list to pick the top N items from. |
topN | Number of items to pick. |
comparator | Comparator with which to rank the items in the list. |
public static ArrayList<?> selectTopN(List<?> originalList, int topN, Comparator<Object> comparator)
//package com.java2s; /* /* ww w . j ava 2 s .c om*/ * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import java.util.*; public class Main { /** * Pick the top N items from the specified list. * * @param originalList The list to pick the top N items from. * @param topN Number of items to pick. * @param comparator Comparator with which to rank the items in the list. * @return A new list containing the top N items. */ public static ArrayList<?> selectTopN(List<?> originalList, int topN, Comparator<Object> comparator) { ArrayList<Object> newList = new ArrayList<Object>(topN); int numIncluded = 0; Object lastObject = null; for (Object o : originalList) { if (numIncluded < topN) { newList.add(o); // allow for ties if (comparator.compare(o, lastObject) != 0) { numIncluded++; lastObject = o; } } } return newList; } }