pringlesinn pringlesinn - 1 month ago 6
Java Question

Checking if Collection contains an Object inside an Object

public class Address{
private TypeAddress typeAddress;
private String street;
//Getters and Setters
...
}

public class TypeAddress{
private String type;
//Getters and Setters
...
}


I have a Collection of Addresses

Collection<Address> addresses = db.getAddresses();


I need to check if is there any address of a type that the costumer will pick.
It's just pretending a situation so you guys will understand.

What I want is, I want to get the address of just one type, that type that the customer picked up. If he picked a type that does not exist, I'll pick another address.
So, I basically need to do 2 loops to check if is there any of its type, and if there is, I'll pick it on the next loop. If it's not, I'll pick another one on the next loop.
Is there a way to use the contains method of a Collection to check if the type of the address is what I want?

Something like:

if(addresses.contains("someType")){//remind that I'm trying to check not the object Address, but the object TypeAddress
//get this address
}else{
//get another address
}

Answer

If you're forced to use a collection (and not a Map like suggested), why can't you just iterate once and store the most "promising" instance as some Address reference:

Address address = null;
for (Address addr : addresses) {
    if ( isBetterThanAlreadyFound(addr, address) ) {
        address = addr;
    }
}


private static boolean isBetterThanAlreadyFound(Address addr, Address alreadyFound) {
    return alreadyFound == null || (addr.isOfDesiredType() && alreadyFound.isNot());
}