Viksraj
Viksraj

Reputation: 46

Convert inner advance for loops to check for null

I have something like this

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)
    }
 }

This code is under assumption that scene and time will never be null. Now, I need to convert it such that any or both of the parameters(scene or time) can be null. So if time is null, the key should be generated with scene and if scene is null, the key should be generated with time.

Please help. I am confused here.

Upvotes: 2

Views: 50

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726779

In your specific case you can achieve the result you want by using a set with a single empty string in place of a null set:

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

This would work as long as you concatenate selectedTime and selectedScene with no delimiters in between them.

Upvotes: 1

Related Questions