Finding an Object in an ArrayList by Property
When dealing with large datasets stored in ArrayLists, finding a specific object based on a certain property can prove challenging. This article explores efficient solutions for this scenario, specifically focusing on searching an ArrayList of Carnet objects by their codeIsin property.
Java 8 Stream Approach:
Java 8 introduced the powerful stream API, providing an elegant and concise way to perform operations on collections. To find an object in an ArrayList by a property, you can utilize the stream() function to create a stream of elements, followed by the filter() function to filter out elements that do not match the desired property. Finally, use the findFirst() function to retrieve the first matching element, or return null if none is found.
public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsIn) { return listCarnet.stream().filter(carnet -> codeIsIn.equals(carnet.getCodeIsin())).findFirst().orElse(null); }
Utility Class Method Approach:
This approach involves creating a utility class with static methods that encapsulate the search logic for different properties. This ensures reusability and modularity. The FindUtils class provides the generic findByProperty() method, which accepts a collection and a predicate function as parameters. The predicate function defines the condition for filtering the collection.
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())); } public static Carnet findByNomTitre(Collection<Carnet> listCarnet, String nomTitre) { return FindUtils.findByProperty(listCarnet, carnet -> nomTitre.equals(carnet.getNomTitre())); } public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsin) { return FindUtils.findByProperty(listCarnet, carnet -> codeIsin.equals(carnet.getCodeIsin())); } }
The above is the detailed content of How to Efficiently Find an Object in a Java ArrayList by Property?. For more information, please follow other related articles on the PHP Chinese website!