Search code examples
javafluent

How to create chained methods in Java


I have a class responsible for controlling the objects created during runtime - it builds them from inputs at swing frames - just as a DAO. It has this method that removes already created objects:

public void removeFrom(Class<?> clazz, int index) {
    for (Map.Entry<String, Object> entry : modelsMap.entrySet()) {
        if (entry.getKey().equals(clazz.getSimpleName())) {
            ((ArrayList<Object>) entry.getValue()).remove(index);
        }
    }
}

Instead of calling this method and passing the referent class and index, I'd like the method call to be like this: dao.removeFrom(MyObject.class).at(myIndex); Guess it's looks like chained methods as the Stream API uses. Glad if anyone can help me!


Solution

  • In this case your removeFrom() method should return wrapper around ((ArrayList<Object>) entry.getValue()). And that wrapper has to have method at(int index) which removes element for given index.

    And you also need to think about corner case when your modelsMap doesn't have entry for a given clazz.