I have got stuck in some issue where I need to traverse through a hierarchy and compare some values and moment I got match need to return the result. Here is my complete use-case
I am getting Collection<Categories> categoryList and A Collection<MyCustomObject>,
MyCustomObject{
// some properties
private Category category
}
I need to compare the code of category with the code of category coming under MyCustomObject and need to send back MyCustomObject with first match.
For this comparison I need to traverse through the hierarchy of Collection i.w if the match is not found in the current category need to get Category list by calling
categoryList.getSuperCategories() and then go upward.
I though of recursive method call but seems like this is not working in my case as if I keep traversing the first category till the root I am not able to keep track of the second one.
I was trying something (not completed nor working correctly)
public ProductAllotmentData getProductAllotmnet(final Collection<CategoryModel> categoryModelList)
{
if (CollectionUtils.isNotEmpty(categoryModelList))
{
final List<ProductAllotment> productAllotmentList = getProductAllotmentEntries();
if (CollectionUtils.isNotEmpty(productAllotmentList))
{
for (final CategoryModel model : categoryModelList)
{
for (final ProductAllotmentData productAllotmentData : productAllotmentList)
{
if (model.getCode().equals(productAllotmentData.getAllotmentCategory().getCode()))
{
return ProductAllotmentData;
}
else
{
return getAllotmentForCategory(model.getAllSupercategories(), productAllotmentyData);
}
}
}
}
}
return null;
}
—
public ProductAllotmentData getAllotmentForCategory(final Collection<CategoryModel> categoryModelList,
final ProductAllotmentData productAllotmentaData)
{
ProductAllotmentData allotmentData = null;
for (final CategoryModel model : categoryModelList)
{
if (model.getCode().equals(productAllotmentData.getAllotmentCategory().getCode()))
{
allotmentEntryData = productAllotmentData;
}
else
{
return getAllotmentForCategory(model.getSupercategories(), productAllotmentData);
}
}
return allotmentEntryData;
}
other option came to my mind is to create a kind of stack and put all categories in that and den pop them one at a time compare them and send back the first match ignoring rest of the items in the stack but i m looking for much better and flexible solution.
Problem
I am not sure how I can traverse hierarchy of each category up to compare its code. getAllotmentForCategory is where i am trying to traverse my category hierarchy.
Any help in this regard is really good
You need to traverse back to child categories when you reach the root. Instead Go directly to root and go down until you find them with recursive method.
like… (the code is not copy paste code)