Re: line suppression with c:forEach
cpanon via JavaKB.com wrote On 05/04/06 16:42,:
Hello
Is it possible to suppress a line from printing out if the a falue is
duplicated? Yes, I know that is loosly worded. How about if you have a
collection that you are iterating over. Members in the collection may have
the same value and I want to prevent printing out the next line if the
previous member is the same as the current one.
Thing prev = null;
for (Iterator it = collection.iterator(); it.hasNext(); ) {
Thing curr = (Thing)it.next();
if (! curr.equals(prev))
System.out.println(curr);
prev = curr;
}
This won't work if the collection can actually contain `null'
as a valid element. If that's the case, you need to work a little
harder:
if (! collection.isEmpty()) {
Iterator it = collection.iterator();
Thing prev = (Thing)it.next();
System.out.println(prev);
while (it.hasNext()) {
Thing curr = (Thing)it.next();
if (curr == null ? prev != null : !curr.equals(prev))
System.out.println(curr);
prev = curr;
}
}
Note that these are solutions to your problem as you've stated
it, which might not be the problem you truly intended. For example,
if the collection holds "A" "B" "A" in that order, the above will
print all three of them (because no two adjacent elements are
equal). If you really only wanted "A" and "B" once each, read up
on the Set interface, or sort the collection first, or use a
collection that's always sorted.
--
Eric.Sosman@sun.com