1

I am looking for help where I'm trying to iterate product having order list(OrderItem) which also contains sub-OrderList(OrderItem) and the same also contains structure inside it (n times).
How to iterate recursively all the orders and search for action having completed and added all the completed Order in the list?

I have done through BFS/DFS but looking for best optimized solution using functional programming in java. TIA.

Main Product

Class ProductOrder
{    
  private List<OrderItem> orderItem = new ArrayList<OrderItem>();    
}

Sub items in product

Also have n sub-items inside it

Class OrderItem{
    private String id;

    private String state;

    private Integer quantity;

    private List<OrderItem> orderItem = new ArrayList<OrderItem>();

}
4
  • and what have you tried so far? Commented Oct 7, 2019 at 15:54
  • I have tried with DFS and BFS way , able to reach at 3 to 1 ms. Looking for effective way on Java 8 with functional programming. Commented Oct 9, 2019 at 7:33
  • @Naman : Can you please help me in this? Commented Oct 9, 2019 at 7:34
  • I think , no one has answer so far !! Commented Oct 11, 2019 at 10:02

1 Answer 1

1

You can solve your problem using Stream API by adding the following method to OrderItem:

public Stream<OrderItem> allItems() {
    return Stream.concat(Stream.of(this), orderItem.stream().flatMap(OrderItem::allItems));
}

You can also solve this problem in a generic way:

public static <E> Stream<E> recursiveStream(
        E input,
        Function<? super E, ? extends Stream<? extends E>> mapper
) {
    return Stream.concat(
            Stream.of(input),
            mapper.apply(input).flatMap(item -> recursiveStream(item, mapper))
    );
}

public static <E> Stream<E> recursiveCollection(
        E input,
        Function<? super E, ? extends Collection<? extends E>> mapper
) {
    return recursiveStream(input, mapper.andThen(Collection::stream));
}

If this solution isn't fast enough, create forEach method, it works a little bit faster, but it's harder to use this method since you can't pipeline operations after it:

public void forEach(Consumer<OrderItem> consumer) {
    consumer.accept(this);
    for (OrderItem item : orderItem) item.forEach(consumer);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.