Skip to content
Advertisement

Is there a way to reduce multiple methods as one method with Function as methode parameter?

I have several methods that are basically all the same except for one method that is called in these methods.

Example:

JavaScript

So the only difference is the method getDB().

Since I don’t want to have this method 10 times, I thought of writing this into a method and then controlling it via the input parameters.

My attempt looks like this:

JavaScript

In method anymatch() I do not get further.

This is how I would want to use it:

JavaScript

What do you think? is this a good approach? What would be the further procedure in the getDeadlines() method

Advertisement

Answer

Just use Supplier to insert the required instance of the List and Function to substitute the getter from DeadlineEntity to T compliant with the getEntityXXX method generic type of the returned List:

JavaScript
JavaScript

Edit: To make the code a bit more readable, I’d filter out all p equal to null first and then simplify the lambda expression and switch the parameters of the equals call in the anyMatch method to be null-safe:

JavaScript
Advertisement