问题描述:

I'm having the following code and what I need to do is to add instance (type object) to the item object list(done in the last if) but I need to find full key match . fromProp and toProp are field type object in this instance (are keys that can be username , customer ,number,f1 etc ). now the code is working on the first match field (in the last if statement), if the first match are found we add the data to the item list but I want to find full key match i.e if i have 3 keys so just when they are fully match than add the 'toEntityInstance' to the item object. How should i do that ?

for (Object fromEntityInstance : fromEntityInstances) {

List<Object> itemObject = new ArrayList<Object>();

for (String[] prop : depPropMappings) {

// Get properties related keys

fromProp = prop[0];

toProp = prop[1];

Object fromValue = getInstanceValue(fromProp, fromEntityInstance);

for (Object toEntityInstance : toEntityInstances) {

Object toValue = getInstanceValue(toProp, toEntityInstance);

if (fromValue.equals(toValue)) {

itemObject.add(toEntityInstance);

}

}

}

for example the entities can be

fromEntityInstance

f1=Mark

f2=abc

f3=test1

f4=test1

f5=test1

toEntityInstance

f1=Mark

f2=abc

f3=test1

f4=test1

f5=test1

f1=Mark

f2=abc

f3=test1

f4=test1

f5=test1

f1=jhon

f2=yyyy

f3=test1

f4=test1

f5=test1

and in the depPropMappings i have two instances for keys

first instance

 fromProp = f1;

toProp = f1;

second instance

 fromProp = f2;

toProp = f2;

so I need to add just the two first enities (where f1=mark & f2=abc ) from toEntityInstance to the itemObject . currently the code work if we found the match between f1 but ignore the F2...

i think to count the num of key at the begining and if the num of the key are are indentica l update the list but not sure how to do that

网友答案:

Your loop nesting has the wrong order. Your current code will add toEntityInstance to the list twice if both depPropMappings match. Try something like this:

for (Object fromEntityInstance : fromEntityInstances) {

    List<Object> itemObject = new ArrayList<Object>();

    for (Object toEntityInstance : toEntityInstances) {
        boolean matches = true;

        for (String[] prop : depPropMappings) {

            // Get properties related keys
            fromProp = prop[0];
            toProp = prop[1];

            Object fromValue = getInstanceValue(fromProp, fromEntityInstance);
            Object toValue = getInstanceValue(toProp, toEntityInstance);

            // Note: Make sure that fromValue cannot be null. If this cannot be
            // guaranteed, add a check here.
            if (!fromValue.equals(toValue)) {
                // if any value mismatches, we can stop checking the remaining
                // properties.
                matches = false;
                break;
            }
        }

        if (matches) {
            // all properties match
            itemObject.add(toEntityInstance);
        }
    }
}
相关阅读:
Top