Re: line suppression with c:forEach
- From: Eric Sosman <Eric.Sosman@xxxxxxx>
- Date: Thu, 04 May 2006 17:23:24 -0400
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@xxxxxxx
.
- References:
- line suppression with c:forEach
- From: cpanon via JavaKB.com
- line suppression with c:forEach
- Prev by Date: Re: line suppression with c:forEach
- Next by Date: NullPointer being thrown despite check
- Previous by thread: Re: line suppression with c:forEach
- Next by thread: NullPointer being thrown despite check
- Index(es):
Relevant Pages
|