简体   繁体   English

如何从 java 中的 Collectors.groupingBy 返回不可修改的 map?

[英]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.所以我有一个 map ,它将 Long 作为键,将列表作为值。 I want both the map and the list in each entry to be unmodifiable.我希望 map 和每个条目中的列表都是不可修改的。

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() .对于不可修改的列表, groupingBy将收集器作为可选的第二个参数,因此您可以传递Collectors.toUnmodifiableList() ,而不是隐式默认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.对于不可修改的 map,有一个 functioncollectingAndThen,它接受一个collectingAndThen器和一个 function 在最后应用,并返回一个新的收集器。 So you can wrap the groupingBy in that and call unmodifiableMap on it.因此,您可以将groupingBy包装在其中并在其上调用unmodifiableMap

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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