也许你可以使用Matchers.allOf
,Matchers.anyOf
来Matchers.not
表达你的逻辑。
请查看Hamcrest 教程。
逻辑的
allOf - 如果所有匹配器都匹配,则匹配,短路(如 Java &&)
anyOf - 如果任何匹配器匹配,则匹配,短路(如 Java ||)
not - 如果包装的匹配器不匹配则匹配,反之亦然
一个简单的示例:
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;
}
}