Java examples for java.util:Collection Null Element
Return first duplicate value that is not null, or null if there is no such value.
//package com.book2s; import java.util.Collection; import java.util.Iterator; public class Main { public static void main(String[] argv) { Collection c = java.util.Arrays.asList("asdf", "book2s.com"); System.out.println(firstDuplicateValue(c)); }//from w w w. j a v a 2 s . c om /** * 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; } }