java 8 optional method parameters code example

Example 1: java how to make a parameter optional

void foo(String a, Optional<Integer> bOpt) {
    Integer b = bOpt.isPresent() ? bOpt.get() : 0;
    //...
}

foo("a", Optional.of(2));
foo("a", Optional.<Integer>absent());

Example 2: java how to make a parameter optional

//Java 9 and above only    
@SuppressWarnings("unchecked")
    static <T> T getParm(Map<String, Object> map, String key, T defaultValue)
    {
        return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
    }

    void foo(Map<String, Object> parameters) {
        String a = getParm(parameters, "a", "");
        int b = getParm(parameters, "b", 0);
        // d = ...
    }

    foo(Map.of("a","a",  "b",2,  "d","value"));

Tags:

Java Example