how to make optional class arguments in java code example

Example 1: 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"));

Example 2: java how to make a parameter optional

class Foo {
     private final String a; 
     private final Integer b;

     Foo(String a, Integer b) {
       this.a = a;
       this.b = b;
     }

     //...
 }

 class FooBuilder {
   private String a = ""; 
   private Integer b = 0;

   FooBuilder setA(String a) {
     this.a = a;
     return this;
   }

   FooBuilder setB(Integer b) {
     this.b = b;
     return this;
   }

   Foo build() {
     return new Foo(a, b);
   }
 }

 Foo foo = new FooBuilder().setA("a").build();

Tags:

Java Example