1

I've been googling for a while, but I couldn't find the answer I am looking for.

I have a stream of products, and each one of those contains these fields:

private String ID;
private float price;
private int quantity;

I need to change the quantity field of a specific product without consuming the rest of the stream. Is it possible?

How can I search for this element (by product ID) and then change the value of quantity field?

I was thinking I could use .peek(), but I couldn't figure out how to achieve this.

1 Answer 1

5

Assuming that you have a setter method for the quantity, you can use peek to change the value. Test for the product ID you want, then call the setter, all in a lambda expression (a Consumer).

stream.peek( p -> {
    if ("YourID".equals(p.getID()))
    {
         p.setQuantity(newQuantity);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Is it safe to modify a peek element? Aren't peek elements presumably read-only and thread-safe?
just verified that you can modify elements like that using peek. I think when you peek you just ignore return value of the lambda function, but can use setters of the stream element for example

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.