From: laredotornado on
Hi,

I"m using Java 1.5. Given a java.util.List that I know to have at
least one element, what is the best way to check that all elements in
the list are unique ?

Thanks, - Dave
From: Lew on
laredotornado wrote:
> I"m using Java 1.5. Given a java.util.List that I know to have at
> least one element, what is the best way to check that all elements in
> the list are unique ?

That depends largely on what you mean by "best", and somewhat on what you mean
by "check".

If the List contains exactly one element, then you already know that it's
unique, so the real problem doesn't come about until it has at least two elements.

One way is to dump the List into a Set as you iterate through the List, and
for each element see if it's already in the Set. (This is indicated by the
Set#add() returning false.)

If all you need to do is ensure that each element is unique, you can dump the
contents into a Set and use the Set. (The Set implementations with which I'm
familiar have constructors that take a Collection as the argument.)

If you have a choice about whether to use a List in the first place, just
don't, and use a Set instead.

Whether any of these constitute "best" I cannot tell from your question.

--
Lew
From: Mike Schilling on
laredotornado wrote:
> Hi,
>
> I"m using Java 1.5. Given a java.util.List that I know to have at
> least one element, what is the best way to check that all elements in
> the list are unique ?
>
> Thanks, - Dave

boolean areListElementsUnique(List<?> l)
{
return l.size() == new HashSet<Object>(l).size();
}



From: John B. Matthews on
In article
<95bd0b1b-e372-4981-a6cf-eed5a58e4461(a)u19g2000prh.googlegroups.com>,
laredotornado <laredotornado(a)zipmail.com> wrote:

> I'm using Java 1.5. Given a java.util.List that I know to have at
> least one element, what is the best way to check that all elements in
> the list are unique ?

You should be able to construct a Set, say TreeSet, of the List elements
and see if the sizes match.

--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>
From: Lew on
laredotornado wrote:
>> I"m using Java 1.5. Given a java.util.List that I know to have at
>> least one element, what is the best way to check that all elements in
>> the list are unique ?

Mike Schilling wrote:
> boolean areListElementsUnique(List<?> l)
> {
> return l.size() == new HashSet<Object>(l).size();
> }

Sweet.

You could also generify that:

<T> boolean areListElementsUnique( List<T> list )
{
if (list == null || list.size() == 1 )
{
return true;
}
return list.size() == new HashSet <T> (list).size();
}

In this case the generics add nothing except a sense for the programmer that
they're being clever. The 'null' check is important, I swan.

--
Lew