Re: Best way to check if all elements in a List are unique
In article <alpine.DEB.1.10.1003021900150.13870@urchin.earth.li>,
Tom Anderson <twic@urchin.earth.li> wrote:
On Tue, 2 Mar 2010, Lew wrote:
Mike Schilling wrote:
boolean areListElementsUnique(List<?> l)
{
return l.size() == new HashSet<Object>(l).size();
}
laredotornado wrote:
Winner! -
Don't forget to null-check the argument!
The method already does that - if it's null, you get a
NullPointerException.
I thought the idea was to treat empty and unitary lists as unique, not
to mention skirting the size() of null.
Here's a primitive test:
import java.util.*;
public class SetTest {
private static final int MAX = 10000;
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < MAX; ++i) {
names.add(String.valueOf(i + MAX));
numbers.add(Integer.valueOf(i + MAX));
}
for (int i = 0; i < 3; i++) {
test(names);
test(numbers);
}
}
private static <T> void test(List<T> list) {
if (list == null) return;
int s1 = list.size();
long start = System.nanoTime();
int s2 = new HashSet<T>(list).size();
long stop = System.nanoTime();
System.out.println("HashSet: " + s1 + " " + s2
+ " " + (s1 == s2) + dt(stop - start));
start = System.nanoTime();
s2 = new TreeSet<T>(list).size();
stop = System.nanoTime();
System.out.println("TreeSet: " + s1 + " " + s2
+ " " + (s1 == s2) + dt(stop - start));
}
private static String dt(long nanos) {
return String.format("%7.3f ms.", nanos / 1000000d);
}
}
--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>