Nested collection iterator

I have two data structures in Java:
One of them is called DebateAssignment and has 5 DebateTeam objects, each of which is associated with a specific enumeration, which 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 the commands for all assignments, easily moving from assignment to assignment.

How can i do this?

+3
source share
4 answers

Assuming it DebateAssignmenthas something like

public Collection<DebateTeam> getDebateTeams();

Do You Need Iterator<DebateTeam>?

, - :

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...
}
+4

, google-collections/guava:

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

- Multimap<DebateAssignment, DebateTeam>, values(), entries(). JUDGE/PROP1/ .. .

+5

, :

List<DebateAssignment> list = ...
List<DebateTeam> dtList = new ArrayList<DebateTeam>();
for (DebateAssignment da : list) {
    dtList.addAll(da.getTeams());
}
return dtList.iterator();

, , Iterator<DebateTeam>, "" , , ... (. ).

+2

, ArrayList, Iterator, , .

Overriding the iterator () method cannot be an option for the typical type of iterator returned by it.

0
source

Source: https://habr.com/ru/post/1733517/


All Articles