这是我想要执行的一些 sudo 代码。
String[] listA = new String { "a1", "a2"}
String[] listB = new String { null}
String[] listC = new String { "c1", "c2"}
for( String a : listA) {
for( String b : listB) {
for( String c : listC) {
if( a!=null) System.out.print( a);
System.out.print(",");
if( b!=null) System.out.print(b);
System.out.print(",");
if( c!=null) System.out.print(c);
System.out.println("");
}
}
}
我的预期结果是
a1,,c1
a1,,c2
a2,,c1
a2,,c2
但是由于listB为空,代码逻辑无法打印。我尝试条件检查列表并做出如下逻辑的所有可能性。
if( listA != null) {
for( String a : list A) {
if( listB !=null) {
for(String b : listB) {
if( listC != null) {
}
else {
...
}
}
}
else {
....
}
}
}
else {
...... similar code in here
}
我认为这不是解决这个问题的最佳方法。对此有什么想法吗?
最佳答案
你想要的叫做 'product'三组(列表)。但有一点不同的是,当任何一个列表为空时,它将被一个包含“空元素”的集合替换。
// pseudo code
String[] safeList(String[] list) { if list.length == 0 return {''} else return list; }
// carthesian product with a twist
static void safeProductWithATwist(
String[] listA, String[] listB, String[] listC) {
for(String a: safeList(listA))
for(String b: safeList(listB))
for(String c: safeList(listC))
foo(a, b, c);
}
关于java - java中for元素包含null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38604175/