1

Is possible to test multiple condition on each Matched item in a Collection?

I have a collection with given objects:

obj1: property1=A1, property2=B1

obj2: property1=A2, property2=B2

obj3: property1=A3, property2=B3

obj4: property1=A4, property2=B4

I want to check that property1 and property2 have simultaneously specified values.

Thank you for any advice.

Community
  • 1
  • 1
gipinani
  • 14,038
  • 12
  • 56
  • 85
  • 1
    If you create a [custom matcher](http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/CustomMatcher.html) then you can do whatever you want to match the objects. Have you tried this? If so, what happened? – Duncan Jones May 27 '14 at 09:25
  • 1
    Custom property-matching with example code: http://stackoverflow.com/questions/587404/java-finding-objects-in-collections – sina72 May 27 '14 at 09:27

1 Answers1

2

Sure, that's possible. It would look something like this:

Matcher<Item> matcher = new BaseMatcher<Item>() {

    @Override
    public boolean matches(Object item) {
        Item myItem = (Item) item;
        return check(myItem.property1, myItem.property2);
    }

    @Override
    public void describeTo(Description description) {
        // describe it
    }

}

The check function would have to test the combination of property1 and property2. This may be easiest using a HashMap, unless of course there's some way of calculating one from the other or something like that.

blalasaadri
  • 5,990
  • 5
  • 38
  • 58