Question: I have a requirement where in the function takes different parameters and returns unique objects. All these functions perform the same operation. 

ie. 

```
public returnObject1 myfunction( paramObject1 a, int a) {
returnObject1 = new returnObject1();
returnObject1.a = paramObject1.a;
return returnObject1;
}

public returnOject2 myfunction( paramObject2 a, int a){
 returnObject2 = new returnObject2();
 returnObject2.a = paramObject2.a;
 return returnObject2;
}

```

As you can see above, both the function do the same task but they take different parameters as input and return different objects. 

I would like to minimize writing different functions that does the same task. 

Is it possible to write a generic method for this that can substitute the parameters based on the call to the function? 

paramObject and returnObject are basically two classes that have different variables. They are not related to each other.

My objective is that I do not want to do function overloading since the functions do almost the same work. I would like to have a single function that can handle different input and different return output. 

my aim is to do something like this (if possible): 

```
public static < E > myfunction( T a, int a ) {
  // do work
}

```

The return type E and the input T can keep varying.

Answer: 
Make `interface Foo` and implement this `interface` in both `paramObject1` and `paramObject2` class. Now your method should be look like: 

```
public Foo myFunction(Foo foo, int a){
    //Rest of the code.
    return foo;
}

```
you can using the 3rd `apply` method to remove the code duplications, you separate creation & initialization from the `apply` method in this approach. and don't care about which type of `T` is used. for example:

```
returnObject1 myfunction(paramObject1 a, int b) {
    return apply(returnObject1::new, b, value -> {
        //uses paramObject1
        //populates returnObject1
        //for example:
        value.foo = a.bar;
    });
}

returnOject2 myfunction(paramObject2 a, int b) {
    return apply(returnOject2::new, b, value -> {
        //uses paramObject2 
        //populates returnObject2
        //for example:
        value.key = a.value;
    });
}

<T> T apply(Supplier<T> factory, int b, Consumer<T> initializer) {
    T value = factory.get();
    initializer.accept(value);
    //does work ...
    return value;
}

```

*Note* the 2 `myfunction` is optional, you can remove them from you source code, and call the `apply` method directly, for example:

```
paramObject2 a = ...;

returnObject2  result = apply(returnOject2::new, 2, value -> {
    //for example:
    value.key = a.value;
});

```