How to find an object in an ArrayList by property

user1279522 picture user1279522 · Jul 8, 2013 · Viewed 172.4k times · Source

How can I find an object, Carnet, in a ArrayList<Carnet> knowing its property codeIsin.

List<Carnet> listCarnet = carnetEJB.findAll();

public class Carnet {

    private String codeTitre;
    private String nomTitre;
    private String codeIsin;

    // Setters and getters

}

Answer

Menno picture Menno · Jul 8, 2013

You can't without an iteration.

Option 1

Carnet findCarnet(String codeIsIn) {
    for(Carnet carnet : listCarnet) {
        if(carnet.getCodeIsIn().equals(codeIsIn)) {
            return carnet;
        }
    }
    return null;
}

Option 2

Override the equals() method of Carnet.

Option 3

Storing your List as a Map instead, using codeIsIn as the key:

HashMap<String, Carnet> carnets = new HashMap<>();
// setting map
Carnet carnet = carnets.get(codeIsIn);