java - java中for元素包含null

标签 java for-loop null

这是我想要执行的一些 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/

相关文章:

tomcat 7 中的 java.lang.OutOfMemoryError

java - 由按钮组成的面板网格

java - 有没有一种方法可以切换字符串中的字母?

java - 并发 hashmap 和 copyonwritearraylist

session - Swift URL 响应为零

android - Kotlin Elvis Operator 在 JsonElement 上失败?

batch-file - BATCH FOR 命令中的 WMIC 调用返回无法解释的错误

javascript - 嵌套 for 循环始终显示最后的数据

javascript - For 循环工作并返回结果,但随后停止并返回 - TypeError : Cannot read property 'tag' of undefined

ios - Swift:当 ViewController 调用时,TableViewController 中的 UIControl 发现为 nil