Search code examples
javaarraysjava-stream

How to change the value of a String in a nested array of Objects?


I have an object called User. The user object contains array of objects. In the nested array of object there is a key called Status. I want to map or change the value of Status from "NEW" to "PROCESSED".

I have tried to iterate through the values of the nested array of objects and replace the corresponding value of Status from "NEW" to "PROCESSED". I tried the following -

user.positions().listIterator().forEachRemaining(e->e.positionItems().listIterator().
 forEachRemaining(l->{
  l.fulfillmentStatus().replace("NEW","PROCESSED");
 }));

However, the above code is not able to change the value as String is immutable. There is a warning shown with replace that "Result of 'String.replace()' is ignored"


Solution

  • You could replace each PositionItem with a new one with just the fulfillmentStatus changed by using ListIterator#set to change the element at each index.

    order.positions().forEach(e -> {
        for (var it = e.positionItems().listIterator(); it.hasNext();) {
            var curr = it.next();
            it.set(curr.toBuilder().fulfillmentStatus(curr.fulfillmentStatus().replace("NEW","PROCESSED")).build());
        }
    });
    

    As Holger mentions, List#replaceAll can also be used.

    order.positions().forEach(e -> 
        e.positionItems().replaceAll(curr ->
            curr.toBuilder().fulfillmentStatus(
                curr.fulfillmentStatus().replace("NEW", "PROCESSED")
            ).build()
        )
    );