Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Best/elegant way to iterate over 2 lists

Assume I have a List<SomeObject> a.
Now also assume that I have another List<SomeProcessor> b.
Each SomeProcessor uses a for its processing.

Besides:

int idx = 0;   
for(SomeProcessor o:b){  
    o2 = a.get(idx);  
    o.doSomething(o2);  
    idx++;   
}

Is there a more elegant way to handle this?

like image 333
Jim Avatar asked Feb 21 '12 07:02

Jim


1 Answers

public interface Processor<T> {
    public void process(T object);
}

And then a helper method:

public static <T> void processAll(Collection<T> items, Collection<? extends Processor<T>> processors) {
    Iterator<T> i = items.iterator();
    Iterator<? extends Processor<T>> p = processors.iterator();
    while(i.hasNext() && p.hasNext())
        p.next().process(i.next()); 
}

You could put that helper method on the class which uses it, if there is only one (and make it private), or put it a utility class which is shared by the entire program.

Of course there are other ways to code processAll; for example, you could use a for loop on one of the collections. But in any case, breaking this low-level code out into a helper method will make your higher-level code cleaner and less "noisy". And if you are doing something similar in multiple parts of the program, they can share the helper method.

like image 109
Alex D Avatar answered Sep 22 '22 01:09

Alex D