Search code examples
javacollectionsforeachconceptual

How to compare a hashSet within a foreach loop iterating through another hashSet Java


I'm running a test to see if the values I've inputed into a file are the same values I generate from my API. So I have actual values which are generated from my API and I have another list of expected values. The problem I have is that I am not able to make apple to apple comparisons.

Example:

Actual = {red, bleu, yellow, purple}
expected = {bleu, red, purple, yellow}

failure: red != bleu, bleu != red, yellow != purple, purple != yellow 

I'm not sure how else to better describe what I'm saying other than showing you my code.

Here is my code:

TreeSet<String> hashSet = (TreeSet<String>) calcGraph.getInputs();
boolean success = true;
String error="";

for(String xpath : hashSet) {

    String actual = someApi(response, expression, xpath);

    for ( String values : data.getDataOutputs().keySet() ) {
        String expected = data.getDataOutputs().get(expectedXpath);

        if ( !expected.equals(actual)) {
            error+= "\nExpected : " + expected +"\nActual: " +actual+"\n";
            success = false;
        } if ( !success ) Assert.fail(error);

    }
}

How can I compare these lists within 1 foreach loop or equivalent? Any help or assistance would be appreciated.

Edit:

            Iterator<String> expectation = expectedList.iterator();
            Iterator<String> actuation = actualList.iterator();

            while((expectation.hasNext()) && (actuation.hasNext())) {

                String exp = expectation.next();
                String act = actuation.next();

                logger.info("Expected: "+exp);
                logger.info("Actual: "+act);

                // Validation check
                if ( !exp.equals(act)) {
                    error+= "\nExpected : " + exp +"\nActual: " +act+"\n";
                    success = false;
                } if ( !success ) Assert.fail(error);
            }

Order matters, so this will fail...


Solution

  • You can use

    Set.contains(value)
    

    to check if an actual value is in expected value, you only need one for loop to achieve this

    See this

    http://docs.oracle.com/javase/7/docs/api/java/util/Set.html#contains(java.lang.Object)