オプションのorElseでストリーム

アルジュン:

私が使用しようとしていますStream中にorElse、エラーを理解するのに困難を持ちます。

collectorConfiguration = Optional.ofNullable(recapPlacement.getAttId())
    .map(attId -> Optional.ofNullable(processorEngine.buildFrimFromAttId(attId))
         .orElseThrow( () -> new OmegaException("UnableToFirmByAttId", recapPlacement.getAttId())))
    .orElse( () -> Optional.ofNullable(collectorConfigurations.stream() //getting error here
        .filter(cc -> recapPlacement.getPnetCode().equals(cc.getPnetCode()))
        .filter(Objects::nonNull)
        .findFirst())
        .orElseThrow( () -> new OmegaException("CollectorCouldNotMapForPnetCode", recapPlacement.getPnetCode()))
    );

全体的に上記のコードでは私がしようとしています

  1. 取得collectorConfig場合attIdはnullではありません

  2. 場合はattIdnullでなく、collectorConfigそのためには見られないattId、私は例外をスローしています

  3. 場合attIdはnullが、その後で私が使用していますpnet取得するには、コードをcollectConfigストリーミングcollectConfigurationsリスト

  4. 場合collectConfigのために発見されないpnetCode、私は例外をスローしています

これは、コンパイルエラー「与えているTarget type of a lambda expression must be an interfaceで」orElseブロックを。

また:

あなたは交換したいかもしれません

.orElse( () -> Optional.ofNullable(collectorConfigurations.stream() //getting error here

Optional.orElseGetこれを期待Supplier通り:

.orElseGet( () -> Optional.ofNullable(collectorConfigurations.stream() ...

上記に加えて、あなたは必要はありませんOptional.ofNullableサプライヤーに

.orElseGet( () -> collectorConfigurations.stream()
    .filter(cc -> recapPlacement.getPnetCode().equals(cc.getPnetCode()))
    .filter(Objects::nonNull) //non-null filtered
    .findFirst()) // optional
    .orElseThrow( () -> new OmegaException("CollectorCouldNotMapForPnet...

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=206163&siteId=1