Java tutorial
//package com.java2s; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; public class Main { /** * Get the "best" in collection. That is the least if direction is < 0, otherwise the greatest. The first is chosen if there are multiples. * @param <T> * @param <U> * @param c * @param comp * @param direction * @return */ public static <T, U extends Collection<T>> T getBest(U c, Comparator<T> comp, int direction) { Iterator<T> it = c.iterator(); if (!it.hasNext()) return null; T bestSoFar = it.next(); if (direction < 0) { while (it.hasNext()) { T item = it.next(); int compValue = comp.compare(item, bestSoFar); if (compValue < 0) { bestSoFar = item; } } } else { while (it.hasNext()) { T item = it.next(); int compValue = comp.compare(item, bestSoFar); if (compValue > 0) { bestSoFar = item; } } } return bestSoFar; } }