Home > Blockchain >  How to check for an empty Optional array of strings in Java?
How to check for an empty Optional array of strings in Java?

Time:07-28

How can I check for an empty Optional array of strings in Java?

In the case is empty I would like to return a message.

    @PostMapping("/users")
    @ResponseBody
    public String saveUsers(@RequestParam Optional<String>[] paramArray) {
        System.out.println("param "   paramArray);
        String msg = "";
        int i = 0;
        if (paramArray is empty) {
            msg = "paramArray is empty";
        } else {
            for (Optional<String> paramArrayItem : paramArray) {
                msg  = "param["   i   "]"   paramArrayItem   "\n";
                i  ;
            }
        }
        return msg;
    }

CodePudding user response:

Optional<String>[] is an array of Optional<String> elements.

You'd rather want to have optional array of strings, so you need to change paramArray type to Optional<String[]>.

@PostMapping("/users")
@ResponseBody
public String saveUsers(@RequestParam Optional<String[]> paramArray) {
    System.out.println("param "   paramArray);
    String msg = "";
    int i = 0;
    if (paramArray.isEmpty()) {
        msg = "paramArray is empty";
    } else {
        for (String paramArrayItem : paramArray.get()) {
            msg  = "param["   i   "]"   paramArrayItem   "\n";
            i  ;
        }
    }
    return msg;
}
  • Related