Simplifying conditions with Optional.ofNullable()

Viewed 207

I'm wondering if there is an exit in the use of Optional.ofNullable()

for(String name: names){
  if(name != null)
     person = "Mr./Mrs."+name;
  else
      continue;
  greeting(person);
}

My code is like above. I want to check the argument before calling the function. I have similar codes in my class and to reduce complexity I want to use Optional.Nullable().

Is there a way to apply Optional.Nullable() in here? Or is there another way to help me to reduce complexity of multiple if checks to check null variables? Thanks in advance.

2 Answers

My code is like above. I want to check the argument before calling the function. I have similar codes in my class and to reduce complexity I want to use Optional.Nullable().

You have several options depending on your given context:

Approach 1: Rearrange the conditionals

  for(String name: names){
        if(name != null) {
            person = "Mr./Mrs." + name;
            greeting(person);
            ... 
        }
    }

or :

    for(String name: names){
        if(name == null)
            continue;
        person = "Mr./Mrs." + name;
        greeting(person);
        ...
    }

Approach 2: Using Optional

for(String name: names){     
   Optional.ofNullable(name)
           .map("Mr/Mrs"::concat)
           .ifPresent(YourClass::greeting); 
}

the YourClass is just a place holder for the class where the method greeting was defined.

Approach 3: Using Streams

Assuming that names is a Collection, then you are actually better off using Java Streams, namely:

names.stream()
     .filter(Objects::nonNull)
     .forEach(name -> greeting("Mr./Mrs."+name));

If names is an array of Strings then you can do:

Arrays.stream(names)
      .filter(Objects::nonNull)
      .forEach(name -> greeting("Mr./Mrs."+name));

You can involve Optional:

for (String name : names) {
  Optional.ofNullable(name).map(n -> "Mr/Mrs" + name).map(p -> greeting(p));
}

or Streams:

names.stream()
    .filter(Objects::nonNull)
    .map(n -> "Mr./Mrs." + name)
    .forEach(p -> greeting(p));

But there's really no advantage to doing either. It's certainly not more performant to do so.

Related