Java: the best / elegant way to iterate over two lists

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

Moreover:

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

Is there a more elegant way to handle this?

+6
source share
3 answers
 public interface Processor<T> { public void process(T object); } 

And then the 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 can put this helper method in a class that uses it if there is only one (and make it private ), or put it in a utility class that is shared by the entire program.

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

+7
source

If you can generate a Map<SomeObject, SomeProcessor> instead of two lists, then this will be elegant. This may not be applicable, but I will just do it.

+1
source

Perhaps you can try using this simpler way:

 int idx = 0; while(idx<a.size() && idx<b.size()){ b.get(idx).doSomething(a.get(idx++)); } 
+1
source

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


All Articles