简体   繁体   中英

How do I correct this code to make it generic?

I am beginning to learn to code but I don't know how to generate the CRUD Read method that is generic. For the moment to test I am assigning the object to be of type Person in which the ID of the class is the identification card. The problem is when comparing the attribute that is sent by the read method so that it returns only the element of the same ID.

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

What other option can be used instead of the .equals () method because when using this, it returns Optional.empty?

Thank you very much for your help

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM