Search code examples
javalistoptimizationarraylistjava-stream

Java - How to search for a value in the list of objects


For example i have list, class and methods:

List<Client> myClient = new ArrayList<>();
public class Client {
    String firstName;
    String lastName;
    String cID;
    boolean subscription = false;
}
public String activateSubscription(String customerID){
    for( Client myCustomer: myClient ){
        if( myCustomer.cID == customerID ){
            myCustomer.setSubscription();
            break;
        }
    }

    return null;
}

public void getClientName(String customerID){
    String nameCustomer = null;

    for( Client myCustomer: myClient ){
        if( myClient.clientID == customerID ){
            nameCustomer = myCustomer.getFullName();
            break;
        }
    }

    return nameCustomer;
}

public int getNumberOfSubsrtipion(){
    int count = 0;

    for( Client myCustomer: myClient ){
        if( myCustomer.getSubscription ){
            count += 1;
        }
    }

    return count;
}

I'm new to Java, and I wondering if it's possible to simplify this code?

Maybe there's a simpler way to count subscribed customers and searching for customers by ID?


Solution

  • Using Streams you can simplify it yes

    public long getNumberOfSubscription() {
        return myClient.stream().filter(Client::getSubscription).count();
    }
    
    public void activateSubscription(String customerID) {
        myClient.stream().filter(c -> c.getcID().equals(customerID))
                .findFirst()
                .ifPresent(client -> client.setSubscription(true));
    }
    
    public String getClientName(String customerID) {
        return myClient.stream().filter(c -> c.getcID().equals(customerID))
                .map(Client::getFullName).findFirst().orElse(null);
    }