Java tutorial
//package com.java2s; import java.util.Collection; import java.util.Iterator; public class Main { /** * Return first duplicate value that is not null, or null if there is no * such value. Even logic is similar to hasDuplicateValues, code had to be * duplicated because of different handling of null. * * @param c * to search for duplicate value * @return first duplicate value */ public static <E> E firstDuplicateValue(Collection<E> c) { Iterator<E> iterator = c.iterator(); int idx = 0; while (iterator.hasNext()) { idx++; E e = iterator.next(); if (e != null && iterator.hasNext()) { Iterator<E> subiterator = c.iterator(); // move subiterator to index int sub = 0; while (subiterator.hasNext() && sub < idx) { sub++; subiterator.next(); } // check if others are duplicates while (subiterator.hasNext()) { E s = subiterator.next(); if (e.equals(s)) { return e; } } } } return null; } }