how do i correct a static code to make it generic?

You can define Predicate<P> as an argument:

    public Optional<P> read(Predicate<P> predicate){
        return lista.stream().filter(predicate).findFirst();
    }

And use it like following:

    controladorPersona.read(p -> "0202".equals(p.getCedula()));

Yet anothe option is to create an interface (eg HasId) with a method like String getId() and implement it in the Persona class. Then you can define generic in the ControladorPersona like <P super HasId>. In this case read method might look like:

    public Optional<P> read(String id){
        return lista.stream().filter(p -> id.equals(p.getId())).findFirst();
    }

The idea is to let ControladorPersona know how to extract identifier from an element.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top