[英]Can I iterate for each loop on the basis of specific condition?
Suppose there are two lists of two classes say Class A
and Class B
respectively listOfClassesA
and listOfClassesB
. 假设有两个类别的两个列表,分别是Class A
和Class B
listOfClassesA
和listOfClassesB
。
Now I need to iterate these lists in a single loop on specific condition that suppose boolean variable test is true than iterate list A otherwise B, So I want something like below 现在,我需要在特定条件下(假设布尔变量测试为真)在单个循环中迭代这些列表,而不是迭代列表A否则B,所以我想要以下内容
Boolean test = true;
For( test ? A a:B b : test ? listOfClassesA : listOfClassesB){
String id = test?a.getId():b.getId();
}
I have this requirement because in almost both cases almost all code are same so I dont want to repeat loop two times, but I didn't find any way to do this. 我有这个要求,因为在几乎两种情况下,几乎所有代码都是相同的,因此我不想重复两次循环,但是我没有找到任何方法来执行此操作。 Is there any way to achieve this? 有什么办法可以做到这一点?
No, Java does not let you write a loop like that. 不,Java不允许您编写这样的循环。 What you can do is defining a generic method * , and put a call to that method in a body of your loop. 您可以做的是定义一个通用方法* ,然后在循环体中调用该方法。 This way you would need to repeat only the loop header, and not the code inside the loop body. 这样,您将只需要重复循环头,而不需要重复循环体内的代码。
if (test) {
for (A a : listOfA) loopBody(a);
} else {
for (B b : listOfB) loopBody(b);
}
...
private static <T> void loopBody(T item) {
...
}
You can implement a new class (can be anonymous) implementing the Iterable
interface that will return your iterator responsible for iterating over listOfClassesA
or listOfClassesB
. 您可以实现一个新类(可以是匿名的),该类实现Iterable
接口,该接口将返回负责迭代listOfClassesA
或listOfClassesB
迭代器。 However, in the definition of your iterator you can can only use the class A
and B
common super type. 但是,在迭代器的定义中,您只能使用类A
和B
公共超级类型。
That is what I had on mind: 那就是我的想法:
interface I { }
class A implements I { }
class B implements I { }
class MyIterator implements Iterable<I> {
private List<I> list;
public MyIterator(boolean test, List<A> listOfClassesA, List<B> listOfClassesB) {
super();
this.list = new ArrayList<I>(test ? listOfClassesA : listOfClassesB);
}
@Override
public Iterator<I> iterator() {
return list.iterator();
}
}
public class Test {
public static void main(String[] args) throws Exception {
List<A> listOfClassesA = new ArrayList<A>();
List<B> listOfClassesB = new ArrayList<B>();
for(I elm : new MyIterator(true, listOfClassesA, listOfClassesB)) {
// elm is of I type
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.