Filter by more than one criteria using lambdaj

4.8k Views Asked by At

I am using lamdaj expressions to filter the lists based on certain criteria. Inorder to find matches hamcrest matcher is being used.

My question is, I would like to filter the list based on more than one condition using AND and OR operator and i do not know how to do it.

For example, At present i have the below expression

List<CheckPlanForecastData> filteredSubFleet = select(
                            forecastList,
                            having(on(CheckPlanForecastData.class).getSubFleetCode(),
                            Matchers.equalTo(report.getSubFleet())));

Here i have filtered the list based on getSubFleetCode(). I would like to add another criteria along with getSubFleetCode() which i do not know how construct the expression.

Please help.

2

There are 2 best solutions below

3
On

Maybe you can use Matchers.allOf, Matchers.anyOf and Matchers.not to express your logic.

Please check The Hamcrest Tutorial.

Logical

allOf - matches if all matchers match, short circuits (like Java &&)

anyOf - matches if any matchers match, short circuits (like Java ||)

not - matches if the wrapped matcher doesn't match and vice versa

A simple sample:

import org.hamcrest.Matchers;

import java.util.ArrayList;
import java.util.List;

import static ch.lambdaj.Lambda.having;
import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.Lambda.select;

public class TestLambdaJ {

    public static void main(String[] args) {
        List<Order> orders = new ArrayList<>();
        Order order1 = new Order();
        order1.addItem("Apple");
        order1.addItem("Banana");
        order1.addItem("Orange");
        orders.add(order1);

        Order order2 = new Order();
        order2.addItem("Apple");
        order2.addItem("Cherry");
        order2.addItem("Strawberry");
        orders.add(order2);

        Order order3 = new Order();
        order3.addItem("Olive");
        order3.addItem("Banana");
        order3.addItem("Strawberry");
        orders.add(order3);

        List<Order> ordersWithApple = select(orders,
                having(on(Order.class).getItems(),
                        Matchers.allOf(
                                Matchers.hasItem("Apple"),
                                Matchers.hasItem("Banana"))));
    }
}

class Order {
    List<String> items = new ArrayList<>();

    public void addItem(String item) {
        items.add(item);
    }

    public List<String> getItems() {
        return items;
    }
}
0
On

The return type of having() has two methods to do this sort of chaining: and(Matcher) and or(Matcher). See http://lambdaj.googlecode.com/svn/trunk/html/apidocs/ch/lambdaj/function/matcher/LambdaJMatcher.html.

Best regards, Dietrich