![](/img/trans.png)
[英]Java - How to handle NullPointerException for large sets of nullable fields?
[英]How to join two nullable sets in Java
我有兩個以String作為鍵的映射,並將Set設置為其值。 這兩個地圖可以共享相同的密鑰。 如果兩個映射具有相同的密鑰,我正在嘗試將兩個Set值合並在一起。 問題是,第二個映射可能為null,並且由於並非所有鍵都在兩個映射之間共享,因此Sets也可能為null。 我想出了幾個選項,但它們看起來都很混亂。 想知道是否有人有更高效/更漂亮的方式。 這是我到目前為止:
Set<String> mergedSet = (firstMap.containsKey(commonKey)) ? firstMap.get(commonKey) : new HashSet<String>();
mergedSet.addAll(secondMap != null && secondMap.containsKey(commonKey) ? secondMap.get(commonKey) : new HashSet<String>());
我會使用Guava的HashMultimap而不是Map<String, Set<String>>
。 它具有以下優點:
get(key)
時,始終返回非null Set,即使此鍵沒有存儲任何內容。 所以你的代碼將成為:
Set<String> mergedSet = Sets.union(firstMultimap.get(commonKey),
secondMultimap.get(commonKey));
該集合將簡單地是兩個集合的視圖,這避免了復制每個元素。 但如果你想要一份副本,那就去做吧
Set<String> mergedSet = Sets.newHashSet(Sets.union(firstMultimap.get(commonKey),
secondMultimap.get(commonKey)));
如果您不想使用外部庫,那么您的代碼就可以了。 我會使用Collections.singletonSet()
作為第二個回退集,以避免不必要的空集創建。 並且要小心:您的代碼修改了第一組。 它沒有復制它。 所以最后,第一張地圖的每一組實際上都是一個合並的集合。
在某種程度上,這更像是一種風格問題,但有幾點需要評論。 首先, containsKey
和get
方法具有相同的開銷,因此調用get
並檢查null返回值更有效。 其次,在您的示例中,將mergedSet
設置為firstMap.get(commonKey)
,這意味着您將在firstMap
修改集合,它將是合並集合。 我猜你不想在firstMap
修改集合。 我建議使用更長的時間:
Set<String> mergedSet = new HashSet<String>();
Set<String> firstSet = firstMap.get(commonKey);
if (firstSet != null)
{
mergedSet.addAll(firstSet);
}
if (secondMap != null)
{
Set<String> secondSet = secondMap.get(commonKey);
if (secondSet != null)
{
mergedSet.addAll(secondSet);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.