Java流.orElseThrow

spa*_*kai 5 java optional java-stream

我想从我一直在努力使用流的连接池项目中转换一段代码

原始代码是

for (Map.Entry<JdbConnection,Instant> entry : borrowed.entrySet()) {
  Instant leaseTime = entry.getValue();
  JdbConnection jdbConnection = entry.getKey();
  Duration timeElapsed = Duration.between(leaseTime, Instant.now());
  if (timeElapsed.toMillis() > leaseTimeInMillis) {
    //expired, let's close it and remove it from the map
    jdbConnection.close();
    borrowed.remove(jdbConnection);

    //create a new one, mark it as borrowed and give it to the client
    JdbConnection newJdbConnection = factory.create();
    borrowed.put(newJdbConnection,Instant.now());
    return newJdbConnection;
  }
}

throw new ConnectionPoolException("No connections available");
Run Code Online (Sandbox Code Playgroud)

我已经明白了这一点

borrowed.entrySet().stream()
                   .filter(entry -> Duration.between(entry.getValue(), Instant.now()).toMillis() > leaseTimeInMillis)
                   .findFirst()
                   .ifPresent(entry -> {
                     entry.getKey().close();
                     borrowed.remove(entry.getKey());
                   });


JdbConnection newJdbConnection = factory.create();
borrowed.put(newJdbConnection,Instant.now());
return newJdbConnection;
Run Code Online (Sandbox Code Playgroud)

以上可以编译,但我得到以下orElseThrow后添加的那一刻IfPresent

/home/prakashs/connection_pool/src/main/java/com/spakai/ConnectionPool.java:83: error: void cannot be dereferenced
                       .orElseThrow(ConnectionPoolException::new);
Run Code Online (Sandbox Code Playgroud)

Dav*_*rad 14

那是因为ifPresent返回无效.它无法链接.你可以这样做:

Entry<JdbConnection, Instant> entry =
    borrowed.entrySet().stream()
        .filter(entry -> Duration.between(entry.getValue(), Instant.now())
                            .toMillis() > leaseTimeInMillis)
        .findFirst()
        .orElseThrow(ConnectionPoolException::new));
entry.getKey().close();
borrowed.remove(entry.getKey());
Run Code Online (Sandbox Code Playgroud)

你在寻找什么会读得很好:

.findFirst().ifPresent(value -> use(value)).orElseThrow(Exception::new);
Run Code Online (Sandbox Code Playgroud)

但为了它的工作,ifPresent将不得不返回Optional,这将有点奇怪.这意味着你可以一个ifPresent接一个地链接,对值进行多次操作.这可能是一个很好的设计,但它并不是创造者所Optional采用的.