How to return an unmodifiable map from Collectors.groupingBy in java?

Viewed 576

So I have a map that takes a Long as a key and a list as a value. I want both the map and the list in each entry to be unmodifiable.

Map<Long, List<VariantValueDto>> variantValues = productVariantValues.stream()
    .map(p -> new VariantValueDto(
        p.getProductVariantId(), p.getOptionId(), p.getOptionName(), p.getOptionValueId(), p.getValueName()
    ))
    .collect(Collectors.groupingBy(VariantValueDto::getProductVariantId));

how to return such results?

1 Answers

For the unmodifiable list, groupingBy takes a collector as an optional 2nd argument, so you can pass Collectors.toUnmodifiableList(), rather than the implicit default toList().

For the unmodifiable map, there is a function collectingAndThen which takes a collector and a function to be applied at the end, and returns a new collector. So you can wrap the groupingBy in that and call unmodifiableMap on it.

Map<Long, List<VariantValueDto>> variantValues = productVariantValues.stream()
    .map(p -> new VariantValueDto(...))
    .collect(
        Collectors.collectingAndThen(
            Collectors.groupingBy(
                VariantValueDto::getProductVariantId,
                Collectors.toUnmodifiableList()
            ),
            Collections::unmodifiableMap
         )
    );
Related