Quik19
Quik19

Reputation: 362

Java Streams - Change field of an element

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.

Upvotes: 1

Views: 2091

Answers (1)

rgettman
rgettman

Reputation: 178253

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);
    }
});

Upvotes: 5

Related Questions