How to print objects from a TreeSet

kwoebber picture kwoebber · May 13, 2012 · Viewed 18.5k times · Source

I want to print the instance variables of the objects I stored in my TreeSet.

So given an Object with three instance variables, I want to iterate over the Objects in my TreeSet and print their ivars but:

while ( iter.hasNext() )
{
  System.out.println( iter.next().getIvar1 );
  System.out.println( iter.next().getIvar2 );
}

gets me the ivar1 of the first object and the ivar2 of the second object. And with all my searching I found no way of printing all the ivars of one object before moving the iterator to the next object like:

while ( iter.hasNext() )
{
  System.out.println( iter.hasNext().getIvar1() );
  System.out.println( iter.getIvar2 );
  System.out.println( iter.getIvar3 );
  System.out.println( iter.hasNext().getIvar1() );
  ....
}

Any ideas on how to implement that?

Thanks in advance! =)

Answer

Óscar López picture Óscar López · May 13, 2012

Use an enhanced for loop:

for (Element element : set) {
    System.out.println(element.getIvar1());
    System.out.println(element.getIvar2());
}

Internally, it's just an iterator - but it saves you the trouble of manually calling next() and hasNext().