0

如何合并两个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);

我想将上面的静态最终集组合成一个集合(单语句初始化),因为它是一个Class变量

public static final Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD = ?
4

5 回答 5

4

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());
于 2020-08-03T10:12:33.337 回答
2

只是要指出,Guava 仍然比仅 JDK 的解决方案更具可读性(并且可能性能更高):

public static final Set<Long> SUBSCRIBER_ALLOWED_NUMBER_CD = ImmutableSet.builder()
    .addAll(ORG_SUBSCRIBER_ALLOWED_NUMBER_CD)
    .addAll(INDIVIDUAL_SUBSCRIBER_ALLOWED_NUMBER_CD)
    .build();
于 2020-08-03T10:22:59.263 回答
2

如果你想使用流:

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());
于 2020-08-03T10:11:44.680 回答
1

单语句初始化,如果愿意的话:

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如果预计第三组不可修改,则忽略该调用。

于 2020-08-03T10:11:06.877 回答
1

为什么你不能创建第三组而只添加最后两个组?

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只是意味着您不能修改这些组。它不会阻止您将这些集合读入另一个新集合。

于 2020-08-03T10:05:06.090 回答