亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 lambda 時處理空指針

使用 lambda 時處理空指針

慕桂英546537 2022-12-21 14:44:47
nullPointerException除非e.getKey()返回,否則下面的代碼會得到嗎nullMap<Integer, Optional<SecurityAttributeChange>> spnCreationDetails;Optional.ofNullable(spnCreationDetails.get(e.getKey()).orElse(new SecurityAttributeChange()).getNewAttribute())                                    .orElse(new SecurityAttr())                                    .getUserName());我在這一行中遇到了 NPE,是否可以調試它?我知道spnCreationDetails.get(e.getKey())返回 null,我null在這里處理時遺漏了什么嗎?- 編輯這是幾乎完整的方法,它將有助于提供有關如何重構它以使其可讀的輸入。private void updateAuditFields(List<SecurityAttributeChange> securityChanges, Map<Integer, Map<String, Object>> result) {    Map<Integer, Optional<SecurityAttributeChange>> spnModificationDetails = ...    Map<Integer, Optional<SecurityAttributeChange>> spnCreationDetails = ...    result.entrySet().stream().forEach(e -> {        e.getValue()                .put("userIdLastChanged",                        Optional.ofNullable(Optional.ofNullable(spnModificationDetails.get(e.getKey()))                                .orElse(Optional.of(new SecurityAttributeChange()))                                .get()                                .getNewAttribute()).orElse(new SecurityAttr()).getUserName());        e.getValue()                .put("lastChangedDatetime",                        Optional.ofNullable(Optional.ofNullable(spnModificationDetails.get(e.getKey()))                                .orElse(Optional.of(new SecurityAttributeChange()))                                .get()                                .getNewAttribute()).orElse(new SecurityAttr()).getKnowledgeBeginDate());        e.getValue()                .put("userIdCreated", Optional.ofNullable(                        Optional.ofNullable(spnCreationDetails.get(e.getKey())).orElse(Optional.of(new SecurityAttributeChange())).get().getNewAttribute())                        .orElse(new SecurityAttr())                        .getUserName());    });}
查看完整描述

1 回答

?
泛舟湖上清波郎朗

TA貢獻1818條經驗 獲得超3個贊

如果spnCreationDetails.get(e.getKey())可以為空,您可能需要:

Optional.ofNullable(spnCreationDetails.get(e.getKey()))
        .orElse(new SecurityAttributeChange())
        .getNewAttribute()
        .orElse(new SecurityAttr())
        .getUserName();

iespnCreationDetails.get(e.getKey())應該用Optional.

編輯:看到您的評論,spnCreationDetails.get(e.getKey())可以返回 anull或 an Optional<SecurityAttributeChange>,因此最好只將 thenull轉換為 new Optional

spnCreationDetails.getOrDefault(e.getKey(),Optional.empty())
                  .orElse(new SecurityAttributeChange())
                  .getNewAttribute()
                  .orElse(new SecurityAttr())
                  .getUserName();


查看完整回答
反對 回復 2022-12-21
  • 1 回答
  • 0 關注
  • 297 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號