Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterator over nested collections

I have two data structures in Java:
One is called DebateAssignment and has 5 DebateTeam objects, each associated with a specific enum that includes

{JUDGE, PROP1, PROP2, OP1, OP2}

In another class I use List<DebateAssignment> and I want to create an iterator that will point to a specific DebateTeam in a specific DebateAssignment and I want it to iterate over all teams over all assignments, going from an assignment to assignment seamlessly.

How would I go about doing that?

like image 476
Amir Rachum Avatar asked Dec 22 '22 05:12

Amir Rachum


2 Answers

One way, using google-collections / guava:

return Iterables.concat(Iterables.transform(assignments,
    new Function<DebateAssigment, Collection<DebateTeam>>() {
      public Collection<DebateTeam> apply(DebateAssignment assignment) {
        return assignment.getDebateTeams();
      }
    }));

Another way is to store the data as a Multimap<DebateAssignment, DebateTeam>, then simply iterate over either the values() or entries() view. That data structure won't model the JUDGE/PROP1/etc. association, though.

like image 143
Kevin Bourrillion Avatar answered Dec 28 '22 05:12

Kevin Bourrillion


Assuming DebateAssignment has something like

public Collection<DebateTeam> getDebateTeams();

You want an Iterator<DebateTeam>?

If so, would you want something like:

public class DebateTeamIterator implements Iterator<DebateTeam> {
    private Iterator<DebateAssignment> iAssignment;
    private Iterator<DebateTeam> iTeam;

    public DebateTeamIterator(Iterator<DebateTeam> iAssignment) {
        this.iAssignment = iAssignment;
        if (iAssignment.hasNext())
            iTeam = iAssignment.next().getDebateTeams().iterator();
        else
            iTeam = new LinkedList<DebateTeam>().iterator();
    }

    public boolean hasNext() {
       return iTeam.hasNext() || iAssignment.hasNext();
    }

    public DebateTeam next() {
        if (!iTeam.hasNext())
            iTeam = iAssignment.next().getDebateTeams().iterator();
        return iTeam.next();
    }

    // ... other methods removed for brevity...
}
like image 32
Clinton Avatar answered Dec 28 '22 06:12

Clinton