aspose file tools*
The moose likes Beginning Java and the fly likes How to iterate a Set (2 steps once) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to iterate a Set (2 steps once)" Watch "How to iterate a Set (2 steps once)" New topic
Author

How to iterate a Set (2 steps once)

Andrei Antonescu
Ranch Hand

Joined: Jul 08, 2010
Posts: 75
Hello,

Can you please tell me if there is any way of iterating over a Set making 2 steps at once?
I would like the equivalent of :



but for a Set collection.

Thanks in advance
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11314
    
  16

what's wrong with using an iterator, and just calling next() twice?


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

Of course ensuring that there is an even number of elements, or by checking hasNext() before calling next again.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

Every element in a Set is distinct, so my question is why would you be skipping over elements? And if the elements don't matter why cant you just use an array?

Hunter


"If the facts don't fit the theory, get new facts" --Albert Einstein
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
If you have named your variables correctly, you are not iterating a Set but a List.
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

"equivalent of"
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
David Newton wrote:"equivalent of"
Yes, I missed that. But Fred has already given a good answer.
Andrei Antonescu
Ranch Hand

Joined: Jul 08, 2010
Posts: 75
Hello,

Thank you all for your replies. I will call next() twice.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
Maybe better to try thisOtherwise you may suffer an exception.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19696
    
  20

That's what I already said.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38873
    
  23
Rob Prime wrote:That's what I already said.
Yes, but I only ever notice your posts when they are 5 seconds ahead of mine, not 3 days
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How to iterate a Set (2 steps once)