2

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.

Durgesh Suthar
  • 2,914
  • 4
  • 19
  • 22

3 Answers3

5

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));
}    
Marco13
  • 53,703
  • 9
  • 80
  • 159
4
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();
andrucz
  • 1,971
  • 2
  • 18
  • 30
0

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.

Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44
  • 2
    Then you hurt reusability of Address class. Equals method should verify city, pincode and state to be consistent. – andrucz Feb 08 '16 at 13:13
  • @andrucz it's depend on OP requirement how he wants his Address to be equal – Shekhar Khairnar Feb 08 '16 at 13:15
  • Yes, but it's not generally a good ideia to make equals and hashCode method based on how object will be used in a specific place. Considering that exist simple ways to do what OP wants without hurting reusability, I would avoid doing like your in answer. – andrucz Feb 08 '16 at 13:20
  • @ShekharKhairnar: andrucz is correct. Many other classes use Address class, and there this is not the case. – Durgesh Suthar Feb 08 '16 at 13:32
  • 1
    @Durgesh Suthar: It's totally depends on the requirement and functionality. If your requirement for the equality is specific for a particular attribute for this case only you can go ahead with andrucz solution. – Shekhar Khairnar Feb 08 '16 at 13:41