Recursively merge list of java objects with inner list of same class

Viewed 26

i have a Java Model Class Item:

public class Item {

    @JsonProperty(value = "id", required = true)
    private String id;

    @JsonProperty(value = "name", required = true)
    private String name;

    @JsonProperty(value = "result", required = false)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    LinkedHashMap<String, Integer> result;

    @Nullable
    @JsonProperty(value = "items", required = false)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    List<Item> items;
    
    ...
    Getter/Setter
}

As a starting point I have a list of items List<Item> that I now want to merge recursively, since some of the items have the same ID. But the whole recursively over all hierarchy levels, because each item could have a child list of the same type List<Item>.

I have already tried a few things, but I can't make any progress. Does anyone have ideas how to implement this?

Thanks!

1 Answers

I was there in such situation where we need to parse recursive structure. Additional requirement I had is to preserve the order.

Following sample code (replaced my class with yours)

public static List< Item > getItems(Item item) {
        Deque< Item > auxiliaryStack = new LinkedList<>();
        Deque< Item > finalStack = new LinkedList<>();
        auxiliaryStack.push(item);
        while (!auxiliaryStack.isEmpty()) {
            Item currentItem = auxiliaryStack.pop();
            List<Item> subItems = currentItem.getItems();
            if (CollectionUtils.isNotEmpty(Item)) {
                subItems.forEach(auxiliaryStack::push);
            }
            finalStack.push(currentItem);
        }
        return new ArrayList<>(finalStack);
    }

Now here I wanted to preserve order and duplicates hence I used list. You can use Set to avoid duplicates.

Hope it helps.

Note: Recursive solutions is not production if your data is not fixed. The solution I implemented is iterative and won't fail even nested items goes on and on. Java has stack size limits, though you can increase it , it may affect performance of the whole system.

Related