简体   繁体   English

Java:迭代2个列表的最佳/优雅方式

[英]Java: Best/elegant way to iterate over 2 lists

Assume I have a List<SomeObject> a . 假设我有一个List<SomeObject> a
Now also assume that I have another List<SomeProcessor> b . 现在还假设我有另一个List<SomeProcessor> b
Each SomeProcessor uses a for its processing. 每个SomeProcessor使用a进行处理。

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? 有更优雅的方式来处理这个问题吗?

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. 您可以将该帮助器方法放在使用它的类上,如果只有一个(并使其成为private ),或者将它放在由整个程序共享的实用程序类中。

Of course there are other ways to code processAll ; 当然还有其他方法来编码processAll ; for example, you could use a for loop on one of the collections. 例如,您可以在其中一个集合上使用for循环。 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. 如果你在程序的多个部分做类似的事情,他们可以共享帮助方法。

If you can generate a Map<SomeObject, SomeProcessor> instead of two lists, then it'll be elegant. 如果你可以生成Map<SomeObject, SomeProcessor>而不是两个列表,那么它将是优雅的。 This may not apply, but I'll just give it a shot. 这可能不适用,但我会试一试。

Maybe you can try with this simpler way : 也许你可以尝试这种更简单的方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM