Skip to content

[BUG]Order in collection is not preserved while using useImmutableCollections option #153

@pawellabaj

Description

@pawellabaj

When a record has a component of the type that is the Set implementation keeping the order, the order is lost when using useImmutableCollections = true option.

Following test shows the problem:

import io.soabase.recordbuilder.core.RecordBuilder;

import java.util.Set;

@RecordBuilder
@RecordBuilder.Options(useImmutableCollections = true)
record OrderedSetRecord(Set<String> orderedSet) {}
import org.junit.jupiter.api.Test;

import java.util.LinkedHashSet;

import static org.assertj.core.api.Assertions.assertThat;

public class TestOrderedSetsBuilder {

    @Test
    void shouldKeepOrderInSetIfProvided() {
        // given
        var orderedSet = new LinkedHashSet<String>();
        orderedSet.add("C");
        orderedSet.add("B");
        orderedSet.add("A");

        // when
        var record = OrderedSetRecordBuilder.builder().orderedSet(orderedSet).build();

        // then
        assertThat(record.orderedSet()).containsExactly("C", "B", "A");
    }
}

Order is lost in java.util.Set#copyOf method used in generated __set method.

One of possible solution is te generate __set method as follow:

private static <T> Set<T> __set(Collection<? extends T> o) {
        return (o != null) ?  Collections.unmodifiableSet((Set<T>) o) : Set.of();
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions