Imagine you have a domain-object which is organized in a tree structure. Additionally there are detached objects that reference a part of this structure. Now you need to collect some value from the referenced portion of the tree. You can identify the TreeOrganizedObjects by their UUID. Here is how you can do it in Java:

 

 

protected BigDecimal getValueFromTreeByDetachedEntityReference(final RootEntity rootEntityWithTreeStructure, final List<RootEntityReference> detachedTreeReferencingEntities)
{
    Map<TreeOrganizedObject, List<TreeOrganizedObject>> referencedTree = new HashMap<>();
    final Map<UUID, TreeOrganizedObject> rootTreeReferences = rootEntityWithTreeStructure.getIdsDeep();
    for (RootEntityReference referencingEntity : detachedTreeReferencingEntities)
    {
        TreeOrganizedObject rootTreeObjectOpt = rootTreeReferences.entrySet()
                .stream()
                .filter(entry -> entry.getKey().getUUID().equals(referencingEntity.getUUID()))
                .map(Entry::getValue)
                .findFirst()
                .orElse(null);

        if (rootTreeObjectOpt != null)
        {
            TreeOrganizedObject rootTreeReferencedRootObject = rootTreeObjectOpt.getRootObjectOpt();
            if (rootTreeReferencedRootObject != null)
            {
                if (!referencedTree.containsKey(rootTreeReferencedRootObject))
                {
                    referencedTree.put(rootTreeReferencedRootObject, new ArrayList<>());
                }
                referencedTree.get(rootTreeReferencedRootObject).add(rootTreeObjectOpt);
            }
        }
    }

    BigDecimal result = BigDecimal.ZERO;

    if (!referencedTree.isEmpty())
    {
        for (TreeOrganizedObject rootObject : referencedTree.keySet())
        {
            if (!referencedTree.get(rootObject).isEmpty())
            {
                DomainCalculator calculator = DomainCalculator.create();
                for (TreeOrganizedObject childObject : referencedTree.get(rootObject))
                {
                    result = calculator.add(result, childObject);
                }
            }
        }
    }
    return result;
}