Search code examples
javajava-6

Iterate over multiple Set Java


I want to iterate over a multiple Set.

Set<Pair<Long,Order>> getOrderSet();

This is my method. I am looking for a way to get the values from Order. Order is a class , that has has method like getOrderId() , in which I am interested.

Below is my iterator code.

Iterator iter = getOrderSet().iterator();
while (iter.hasNext()) {
      System.out.println("Order " +iter.next());
}

I am confused how can I obtained the values from Order Class.

Any imputs would be nice.

Thanks !!!


Solution

  • If you use generics, your IDE would be able to help:

    Iterator<Pair<Long,Order>> iter = getOrderSet().iterator();
    while (iter.hasNext()) {
          Pair<Long,Order> pair = iter.next();
          System.out.println("ID " + pair.getFirst());
          System.out.println("Order " + pair.getSecond());
    }
    

    You can also use the "for each" syntax, like this:

    for (Pair<Long,Order> pair : getOrderSet()) {
          System.out.println("ID " + pair.getFirst());
          System.out.println("Order " + pair.getSecond());
    }