Java examples for java.util:Collection Contain
Check if collection has duplicates.
//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(hasDuplicates(c)); }//from w ww .ja v a 2s.co m /** * Check if collection has duplicates. Two null values are also duplicates. * * @param c * to check for duplicates * @return true if collection has duplicates. */ public static <E> boolean hasDuplicates(Collection<E> c) { Iterator<E> iterator = c.iterator(); int idx = 0; while (iterator.hasNext()) { idx++; E e = iterator.next(); // do not check last if (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 == s || (e != null && e.equals(s))) { return true; } } } } return false; } }