1
List<Account> list1 = new ArrayList<>();
List<Order> list2 = new ArrayList<>();

list1.stream().forEach(l1 -> list2.stream()
        .forEach(l2 -> {
            if (l1.getOrderId() == l2.getOrderId())
                l1.setStatus(l2.getStatus());
        }));

I was doing like this. It worked fine but now I have another situation where if orderId is not present in list2 set the status as "invalid" for that particular l1. OrderId is unique in both the tables. Hope this gives better understanding.

4
  • 2
    modifying objects while using Streams, in general, is not a good idea. Commented Feb 23, 2020 at 8:39
  • 2
    "I want to code this using Streams" why? Commented Feb 23, 2020 at 8:45
  • 1
    @Andy I want Functional programming. Commented Feb 23, 2020 at 9:58
  • Cool buddy. Thanks Commented Feb 23, 2020 at 11:25

1 Answer 1

2

Edit Thanks for the edit of your question, it makes a lot more sense now. I think that this should do what you’re after:

    list1.forEach(acc -> acc.setStatus(list2.stream()
            .filter(o -> o.getOrderId() == acc.getOrderId())
            .findAny()
            .map(Order::getStatus)
            .orElse("invalid")));

I am using Iterable.forEach() and then Collection.stream() and Optional.map() for a functional way of calculating the status to be set.

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.