Durgesh Suthar February 2016

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.

Answers


andrucz February 2016

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();


Shekhar Khairnar February 2016

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.


Marco13 February 2016

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));
}    

Post Status

Asked in February 2016
Viewed 3,098 times
Voted 10
Answered 3 times

Search




Leave an answer