I want to extract an object from a nested array with lambdaj. My model is a List of "Products" that own an arrays of "Elements":
public class Product {
Element[] elements;
}
public class Element {
String code;
}
Somewhere in my code I have a list of Products, and I want to find an Element with a specific code in my list.
According to this discussion: https://groups.google.com/forum/?fromgroups=#!topic/lambdaj/QQGmY3cVHP8, I may use:
select(myproductList,
having(on(Product.class).getElements()
.contains(selectUnique(elements,
having(on(Element.class).getCode(), equalTo("codeToFind"))));
But unfortunately, this will not compile because getElements()
is an Array and not a Collection...
So I end up with this java code:
for (Product p : products) {
for (Element e : p.getElements()) {
if (e.getCode().equals("codeTofind")) {
return e;
}
}
}
return null;
Is there a way to iterate through nested Arrays with lambdaJ ?
Ok I found a solution:
selectFirst(flatten(extract(products, on(Product.class).getElements())),
having(on(Element.class).getCode(), equalTo("mycode")));
This will first select and flatten all my elements in a unique collection, then filter it on the code property.
I'm not sure it's the best solution from performance point of view: it looks as if all the products and elements are flattened before a full scan is done. (my understanding of Lambdaj is too weak here to be sure)
I think the full java implementation is more efficient because it stop when the first code is matched.