Home > Java > javaTutorial > How to Efficiently Find a Carnet Object in an ArrayList by its codeIsin Property?

How to Efficiently Find a Carnet Object in an ArrayList by its codeIsin Property?

Barbara Streisand
Release: 2024-12-19 13:07:10
Original
861 people have browsed it

How to Efficiently Find a Carnet Object in an ArrayList by its codeIsin Property?

Retrieving Objects from an ArrayList Based on Property Value

The task at hand is to locate a specific object, namely a Carnet instance, within an ArrayList collection by leveraging its unique codeIsin property.

Java 8 Streams Approach

Java 8 introduces streams, which provide a concise and efficient way to work with data collections. To find the desired object:

public static Carnet findByCodeIsIn(Collection<Carnet> listCarnet, String codeIsIn) {
    return listCarnet.stream().filter(carnet -> codeIsIn.equals(carnet.getCodeIsin())).findFirst().orElse(null);
}
Copy after login

This method leverages stream() to traverse the list and filter() to select only the object with the matching codeIsin value. findFirst() retrieves the first matching element, and orElse() returns null if no match is found.

Generic Utility Class Approach

For scenarios where multiple object types (not just Carnet) or multiple search properties (not just codeIsin) are involved, consider creating a utility class to encapsulate the search logic:

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()));
    }
    // Additional methods for other search criteria
}
Copy after login

This approach centralizes the search logic and allows for easy reuse across different object types and search properties.

The above is the detailed content of How to Efficiently Find a Carnet Object in an ArrayList by its codeIsin Property?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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