How do I edit child collections in a copy of a Java `Immutables` object?

84 Views Asked by At

Given a @Value.Immutable-annotated class that contains a collection of immutable objects, what is the most elegant way to create a new copy, where the child objects are modified?

For example, given a company with employees, if I want to set all employee names to uppercase, is this the correct approach, or is there a simpler one?

Company c1 = ImmutableCompany.builder()
    .name("ACME")
    .addEmployees(
        ImmutableEmployee.builder().name("William Shakespeare").build(),
        ImmutableEmployee.builder().name("T.S. Eliot").build()
    )
    .build();

Company c2 = ImmutableCompany.copyOf(c1).withEmployees(
    c1.employees().stream().map(employee ->
        ImmutableEmployee.copyOf(employee).withName(employee.name().toUpperCase())).collect(Collectors.toList())
);

assertThat(c2.employees().get(0).name(), equalTo("WILLIAM SHAKESPEARE"));
assertThat(c2.employees().get(1).name(), equalTo("T.S. ELIOT"));

This gets fairly unreadable in my real-world scenario, where the property being edited is buried three levels away from the parent node (the company), so I am just trying to make sure I there isn't a simpler approach that I'm missing.

0

There are 0 best solutions below