java - 转换内部 advance for 循环以检查 null

标签 java for-loop set

我有这样的东西

Set<String> scene = myClass.getScene();
Set<String> time = myClass.getTime();
Set<String> possibleKey= new HashSet<String>();
for(String selectedTime: time){
   for(String Selectedscene: scene) {
      String key = selectedTime+selectedScene;
      possibleKey.add(key)
    }
 }

此代码假设场景和时间永远不会为空。现在,我需要将其转换为任何一个或两个参数(场景或时间)可以为空。因此,如果时间为空,则应使用场景生成 key ,如果场景为空,则应使用时间生成 key 。

请帮忙。我在这里很困惑。

最佳答案

在您的特定情况下,您可以通过使用带有单个空字符串的集合代替 null 集合来实现您想要的结果:

Set<String> single = new HashSet<String>();
single.add("");
if (time == null) {
     time = single;
}
if (scene == null) {
     scene = single;
}

只要您连接 selectedTimeselectedScene 并且它们之间没有分隔符,这就可以工作。

关于java - 转换内部 advance for 循环以检查 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39059015/

相关文章:

javascript - JSX:两个 JSX 集之间的差异

Javascript:设置对象属性

java - 如何更改TextInputEditText的底线颜色和提示颜色?

java - Java 中 Do-While 循环的 ExecutorService

javascript - 未捕获的类型错误 : items is not iterable

python - 使用 for 循环将列表值插入嵌套字典中的空列表中

java - 用整数填充(树)集的最短方法?

java - LocationListener 中的 onStatusChanged(String,int,Bundle) 已被弃用

java - 无法正确导入java的opencsv模块[com.opencsv包不存在]

java - 我的算法有什么问题给我不正确的重复删除值?