Home > Java > javaTutorial > How to Efficiently Find an Object in an ArrayList by Property Value?

How to Efficiently Find an Object in an ArrayList by Property Value?

Susan Sarandon
Release: 2024-12-06 20:58:13
Original
769 people have browsed it

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);
}
Copy after login

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)
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template