Durgesh Suthar
Durgesh Suthar

Reputation: 3274

How to apply contains function on attribute of a Java Object?

I have Address class as:

public class Address{
    private String city;
    private String pincode;
    private String state;
}

I have an attribute of different object request as private List<Address> transitLocations.

How can I check if transitLocations contains an address which is having state equals to "SomeString" in one line.

PS: Please assume all getters & setters are present in code.
I don't want to override equals because Address class is used at other places too.

Upvotes: 2

Views: 3737

Answers (3)

Marco13
Marco13

Reputation: 54659

Not being sure why solutions using filter and collect have been proposed...

You can use a Predicate and pass it to Stream#anyMatch

public boolean containsAddressWithState(
    Collection<? extends Address> collection, String state)
{
    return collection.stream().anyMatch(a -> a.getState().equals(state));
}    

Upvotes: 5

andrucz
andrucz

Reputation: 2021

public boolean containsAddressWithState(List<Address> list, String state){
    return list.stream().filter(o -> o.getState().equals(state)).findFirst().isPresent();
}

Or, if you really want to do it in one single line:

boolean containsState = transitLocations.stream().filter(o -> o.getState().equals("SomeString")).findFirst().isPresent();

Upvotes: 4

Shekhar Khairnar
Shekhar Khairnar

Reputation: 2691

You can override the public boolean equals(Object o) method of Object class in Address as :

public boolean equals(Object o){
        if(o instanceof Address && ((Address)o).getSomeString().equalsIgnoreCase(this.someString)){
            return true;
        }else {
            return false;
        }
    }

then you can use List.contains(Object o) method of List to verify that element(Address obj) is present or not in the list.

Upvotes: 0

Related Questions