Home >Java >javaTutorial >How to Efficiently Find an Object in an ArrayList by Property Value?
Finding an Object in an ArrayList by Property
Given an ArrayList containing objects of class Carnet, how can we efficiently retrieve a specific object based on the value of a particular property, such as codeIsin?
Solution (Java 8 Streams):
In Java 8, we can leverage streams to perform this operation concisely:
public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsIn) { return listCarnet.stream().filter(carnet -> codeIsIn.equals(carnet.getCodeIsin())).findFirst().orElse(null); }
Utility Class Approach (Optional):
If we need to perform such lookups across many different classes or for varying properties, we can encapsulate this logic in a utility class:
public final class FindUtils { public static <T> T findByProperty(Collection<T> col, Predicate<T> filter) { return col.stream().filter(filter).findFirst().orElse(null); } } public final class CarnetUtils { public static Carnet findByCodeTitre(Collection<Carnet> listCarnet, String codeTitre) { return FindUtils.findByProperty(listCarnet, carnet -> codeTitre.equals(carnet.getCodeTitre())); } // Similar methods for other properties (e.g., findByNomTitre, findByCodeIsIn) }
This approach provides a more reusable solution and allows for easy modification of the search criteria.
The above is the detailed content of How to Efficiently Find an Object in an ArrayList by Property Value?. For more information, please follow other related articles on the PHP Chinese website!