Java tutorial
//package com.java2s; /* * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * PeerfactSim.KOM is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; public class Main { /** * Sorts <code>source</code> and adds the first n entries to * <code>dest</code>. If <code>source</code> contains less than n entries, * all of them are added to <code>dest</code>. * * If adding an entry to <code>dest</code> does not increase the * collection's size, for example if <code>dest</code> is a set and already * contained the inserted contact, an additional entry of * <code>source</code> will be added, if available. This guarantees that * <code>n</code> new, distinct entries are added to collection * <code>dest</code> as long as this can be fulfilled with the contents of * <code>source</code>, and as <code>dest</code> does recognise duplicate * entries. Consequently, this guarantee does not hold for simple lists. * * Both collections may not be <code>null</code>. * * @param <T> * the entry type of the collections. * @param source * the source collection. * @param dest * the destination collection. * @param order * the order in which <code>source</code> is to be sorted. * @param n * the number of new entries that are to be added to * <code>dest</code>. */ public static <T> void copyNSorted(final Collection<? extends T> source, final Collection<? super T> dest, final Comparator<? super T> order, final int n) { final List<? extends T> src = Collections.list(Collections.enumeration(source)); Collections.sort(src, order); final Iterator<? extends T> it = src.iterator(); final int maxEntries = dest.size() + n; while (it.hasNext() && dest.size() < maxEntries) { dest.add(it.next()); } } }