如何在 Java 中合并两个不可修改的集合?

How to merge two unmodifiable Sets in Java?

如何合并两个 unmodifiable static final 集合?

public static final Set<Long> ORG_SUBSCRIBER_ALLOWED_NUMBER_CD = Set.of(COMPANY_GST, GOVERNMENT_BODY_GST);

public static final Set<Long> INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD = Set.of(BUSINESS_PAN, INDIVIDUAL_PAN);

我想把上面的static final sets合并成一个set(one-statement initialization),因为它是一个Class变量

public static final Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD = ?

为什么你不能创建第三个集合而只添加两个最终集合?

Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD = new HashSet<>();
SUBSCRIBER_ALLOWED_NUMBER_CD.addAll(ORG_SUBSCRIBER_ALLOWED_NUMBER_CD);
SUBSCRIBER_ALLOWED_NUMBER_CD.addAll(INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD);

前两组是final只是意味着你不能修改组。它不会阻止您将集合读入另一个新集合。

A​​ one-statement 初始化,如果首选:

public static final Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD = 
     Collections.unmodifiableSet(
        Stream.of(ORG_SUBSCRIBER_ALLOWED_NUMBER_CD, 
                  INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD)
              .flatMap(Set::stream)
              .collect(Collectors.toSet()));

或者,也许更具可读性:

public static final Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD;
static {
    Set<Long> all = new HashSet<>();
    all.addAll(ORG_SUBSCRIBER_ALLOWED_NUMBER_CD);
    all.addAll(INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD);
    
    SUBSCRIBER_ALLOWED_NUMBER_CD = Collections.unmodifiableSet(all);
}

如果第三组预计不会不可修改,请忽略 Collections.unmodifiableSet 调用。

如果你想使用流:

public static final Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD =
    Stream.of(ORG_SUBSCRIBER_ALLOWED_NUMBER_CD, INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD)
        .flatMap(Set::stream)
        .collect(Collectors.toSet());

或者,在您的情况下,如评论中所述,您可以使用 Collectors.toUnmodifiableSet() :

public static final Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD =
    Stream.of(ORG_SUBSCRIBER_ALLOWED_NUMBER_CD, INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD)
        .flatMap(Set::stream)
        .collect(Collectors.toUnmodifiableSet());

Stream#concat 也很有用

Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD  =  
         Stream.concat(ORG_SUBSCRIBER_ALLOWED_NUMBER_CD.stream(),
                       INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD.stream())
                .collect(Collectors.toSet());

只是要指出,与 JDK-only 解决方案相比,Guava 在处理这种情况时仍然更具可读性(并且可能更高效):

public static final Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD = ImmutableSet.builder()
    .addAll(ORG_SUBSCRIBER_ALLOWED_NUMBER_CD)
    .addAll(INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD)
    .build();