Question

I'm trying to filter a list of caroffers Objects which are found in vendor array through lambdaj. But the below code doesn't work. I'm getting empty list.

    String[] vendor = {"FORD","TOYOTA"}; 
    List carsOffers=filter(having(on(CarProviderModel.class).getProviderName(),  hasItemInArray(vendor)),carprvds);

where as the below code works. Only equalTo seems to work for me.

    List carsOffers=filter(having(on(CarProviderModel.class).getProviderName(),  anyOf(equalTo(vendor[0]), equalTo(vendor[1]))),carprvds);

Please help me.

Was it helpful?

Solution

You want isIn:

filter(having(on(CarProviderModel.class).getProviderName(), 
    isIn(vendor)),carprvds);

hasItemInArray kind of does the opposite of what you want - instead of filtering on items where getProviderName() is one of a supplied list of vendor, it's filtering on items where vendor is one of the items returned by getProviderName() - of course getProviderName() (presumably!) doesn't return an array, so you get no matches.

The Hamcrest Matchers class documentation gives examples of both:

isIn:

assertThat("foo", isIn(Arrays.asList("bar", "foo")))

hasItemInArray:

assertThat(new String[] {"foo", "bar"}, hasItemInArray(startsWith("ba")))

(N.B. Note that your code was calling the other overload of hasItemInArray, which is equivalent to hasItemInArray(equalTo(vendor)) - this may make it clearer to you that you were testing for equality with your vendor collection).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top