Victor
Victor

Reputation: 395

Better way to test non null fields

I have an object that contain some fields, I want to check if some fields are not null and not empty. Is there an good way to do that in java 8 or apache utilities...

I don't want do something like

if(myObj.getMyField1 != null || myObj.getMyField1 != "" || myObj.getMyField2 != null || myObj.getMyField2 != "" || myObj.getMyField3 != null || myObj.getMyField3 != "") {} 

this is myObj

@Data // lombok for generating getters and setters
public class Myobj {
   private String myField1;
   private String myField2;
   private String myField3;
   private String myField4;
   private String myField5;

   private AnotherObj myField6;

}

Would you have any suggestions ?

Upvotes: 1

Views: 5785

Answers (3)

holi-java
holi-java

Reputation: 30686

You can using java-8 Stream#anyMatch to checking the strings is whether null or empty. for example:

boolean hasNullOrEmptyString = Stream.of(myField1,myField2,...,myFieldN)
                                     .anyMatch(it-> it==null || it.isEmpty());

OR you can replace lambda expression with method reference expression which the method can be reused later:

boolean hasNullOrEmptyString = Stream.of(myField1,myField2,...,myFieldN)
                                     .anyMatch(this::isNullOrEmptyString);

boolean isNullOrEmptyString(String it){
  return it==null || it.isEmpty();
}

OR as I see your question that marked as spring, and spring already has a utility method StringUtils#isEmpty for check a String whether is null or empty:

boolean hasNullOrEmptyString = Stream.of(myField1,myField2,...,myFieldN)
                                     .anyMatch(StringUtils::isEmpty);

Upvotes: 5

eis
eis

Reputation: 53482

You've tagged this as spring-boot, so I'm assuming you might be using controllers and validating their parameters. If that is the case, just do

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Data
public class Myobj {
   @NotNull
   @Size(min = 1)
   private String myField1;
   @NotNull
   @Size(min = 1)
   private String myField2;
   /* etc */
}

and

@RequestMapping(value = "/some/url", method = POST)
public void yourMethod(@RequestBody @Valid YourObject yourObject) {
    // 
}

Then your object will be validated on instantiation.

Upvotes: 2

Related Questions