views:

203

answers:

4

I have something like this:

something need here  = scope.getConnections();

//getConnections() returns Collection<Set<IConnection>>

I need to iterate through all connections (the stuff that the getConnections() returns)

How to do that ?

+2  A: 
Collection<Set<IConnection>> sets = scope.getConnections();

for (Set<IConnection> set : sets) {
  for (IConnection connection : set) {
     //do something
  }
}
Bozho
And where is your 'generics'?
Mykola Golubyev
The generics was there, but Bozho did not use the code-style properly. I fixed that for him.
Bart Kiers
Ah, yes, sorry. I was in a hurry and didn't check :)
Bozho
+2  A: 
for (Set<IConnection> set : scope.getConnections()) {
   for (IConnection iConnection : set) {
      // use each iConnection
   }
}
Kaleb Brasee
Where is your 'generics'?
Mykola Golubyev
+2  A: 

I would recommend to you not to return connections in the way you do.
Your getConnections has to return only

Collection<IConnection>

public Collection<IConnection> getConnections()
{
    return connections;
}

Inside your class you can select the way you want or need to store them

private Set<IConnection> connections;

Consider double loop as a problem in your class design.
If I as a user of your class has to write double-loop every time I will stop using your class. So will do your colleagues.

for (IConnection connection : provider.getConnections()) 
{
    connection.doAction();
}
Mykola Golubyev
scope.getConnections() is from a referenced library so i can't do that, i am just using it
Omu
Ok. I get it. If you just need all of the connections I would recommend to write a wrapper class or Util method two loop over the connections.
Mykola Golubyev
A: 

The two-nested-for-loops answer is probably all you need, but note that you could also pass the 'connections' collection to Iterables.concat() in google-collections, and get out a single "flattened" iterable.

http://google-collections.googlecode.com

Kevin Bourrillion