使用JDK 11.0.3
. 我有以下代碼片段:
Set<String> allNumbersSet = customerInfoService.getCustomerPhoneNumbers(bankCustomerId);
additionalInformation
.map(info -> info.get(BANK_PE_CUSTOMER_ID_KEY))
.filter(StringUtils::isNotEmpty)
.ifPresent(id -> allNumbersSet.addAll(customerInfoService.getCustomerPhoneNumbers(id))); // fails here
獲取電話號碼的地方只是Collectors.toSet()
:
@Override
public Set<String> getCustomerPhoneNumbers(String customerId) {
return backOfficeInfoClient.getCustByHashNo(customerId).getPropertyLOVs()
.flatMap(property -> property.getValues().values().stream())
.collect(Collectors.toSet());
}
但是,它失敗了:
java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:71)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.addAll(ImmutableCollections.java:76)
at service.impl.UserManagementServiceImpl.lambda$validateNewLogin$3(UserManagementServiceImpl.java:69)
如果我更新如下:
var allNumbersSet = new HashSet(customerInfoService.getCustomerPhoneNumbers(bankCustomerId));
它現在作業正常。
上面的代碼使用有什么問題?你能解釋一下為什么會出現這種情況嗎?
uj5u.com熱心網友回復:
根據JavadocCollectors.toSet()
:
不保證回傳的 Set 的型別、可變性、可序列化性或執行緒安全性。
所以,如果你需要一個可變集合,你應該自己創建一個,以確保它是可變的。
您可以使用您擁有的復制建構式來做到這一點(new HashSet<>(...)
- 不要忘記<>
),或者您可以使用
Collectors.toCollection(HashSet::new)
作為收集器,如鏈接的 Javadoc 中所述。
但是,請注意,一種更符合 Stream-y 的方法是連接兩個流:
Set<String> someNumbersSet = customerInfoService.getCustomerPhoneNumbers(bankCustomerId);
Set<String> allNumbersSet =
Stream.concat(
someNumbersSet.stream(),
additionalInformation
.map(info -> info.get(BANK_PE_CUSTOMER_ID_KEY))
.filter(StringUtils::isNotEmpty)
.map(customerInfoService::getCustomerPhoneNumbers)
.stream()
.flatMap(Collection::stream))
.collect(Collectors.toSet());
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/507081.html