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":
我想用lambdaj从嵌套数组中提取一个对象。我的模型是拥有“元素”数组的“产品”列表:
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:
根据此讨论:https://groups.google.com/forum/?fromgroups =#!topic / lambdaj / QQGmY3cVHP8,我可以使用:
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...
但不幸的是,这不会编译,因为getElements()是一个数组,而不是一个集合......
So I end up with this java code:
所以我最终得到这个java代码:
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 ?
有没有办法用lambdaJ迭代嵌套的数组?
1 个解决方案
#1
0
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)
从性能的角度来看,我不确定它是最好的解决方案:看起来好像所有产品和元素在完全扫描完成之前都是扁平化的。 (我对Lambdaj的理解太弱了,不能确定)
I think the full java implementation is more efficient because it stop when the first code is matched.
我认为完整的java实现更有效,因为它在第一个代码匹配时停止。
#1
0
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)
从性能的角度来看,我不确定它是最好的解决方案:看起来好像所有产品和元素在完全扫描完成之前都是扁平化的。 (我对Lambdaj的理解太弱了,不能确定)
I think the full java implementation is more efficient because it stop when the first code is matched.
我认为完整的java实现更有效,因为它在第一个代码匹配时停止。