简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM