簡體   English   中英

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

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

所以我有一個 map ,它將 Long 作為鍵,將列表作為值。 我希望 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));

如何返回這樣的結果?

對於不可修改的列表, groupingBy將收集器作為可選的第二個參數,因此您可以傳遞Collectors.toUnmodifiableList() ,而不是隱式默認toList()

對於不可修改的 map,有一個 functioncollectingAndThen,它接受一個collectingAndThen器和一個 function 在最后應用,並返回一個新的收集器。 因此,您可以將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