1

I have the following code stub where I'm reading a set of values from properties file. I need to use these values to pass it as arguments to a function only if they aren't NULL.

public static void main(String[] args) {
    String arg1 = "arg1";
    String arg2 = "arg2";
    String arg3 = null;
    String arg4 = "arg4";
    .
    .
    .

    testMethod(arg1, arg2, arg3);
}

public void testMethod(String... values) {

}

In the above code snippet. I want to call testMethod() with arguments arg1, arg2, arg4 only because arg3 is NULL.

The number of arguments may vary. It will not be 4 all the time.

My code should dynamically check if an argument is not NULL and pass it to the testMethod().

Can I achieve this in Java. If Yes, can someone help me ..

1
  • 1
    what you could do is call the testMethod(String... values) method by passing an array of all your variables, and in that method you kind of manually check if the variables are null and which other method you want to call. Commented Jun 3, 2020 at 14:03

3 Answers 3

7

Yeah, there are multiple methods to do this, since the ... syntax is basically short for passing an array of parameters. So, one way to do this would be for example:

testMethod(Arrays.stream(args).filter(Objects::nonNull).toArray(String[]::new))

Sign up to request clarification or add additional context in comments.

Comments

2

You can create a list and fill it with the Strings that are not null, and then pass the list if it is not empty.

Comments

2

You should make a String list containing all the arguments, iterate over it to check for null and then pass the list to testMethod().

Here's a snippet of what I mean:

public static void main(String[] args) {
    // This is only a simple example, you can make it way more efficient depending on your parameters
    List<String> arguments = new ArrayList<>(Arrays.asList("arg1", "arg2", null, "arg4", null, "arg5"));
    // This is what actually removes the "null" values
    arguments.removeAll(Collections.singletonList(null));
    // Then you can call your method
    testMethod(arguments);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.