我想从我一直在努力使用流的连接池项目中转换一段代码
原始代码是
for (Map.Entryentry : 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");
我已经明白了这一点
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;
以上可以编译,但我得到以下orElseThrow
后添加的那一刻IfPresent
/home/prakashs/connection_pool/src/main/java/com/spakai/ConnectionPool.java:83: error: void cannot be dereferenced .orElseThrow(ConnectionPoolException::new);
David Conrad.. 14
那是因为ifPresent
返回无效.它无法链接.你可以这样做:
Entryentry = borrowed.entrySet().stream() .filter(entry -> Duration.between(entry.getValue(), Instant.now()) .toMillis() > leaseTimeInMillis) .findFirst() .orElseThrow(ConnectionPoolException::new)); entry.getKey().close(); borrowed.remove(entry.getKey());
你在寻找什么会读得很好:
.findFirst().ifPresent(value -> use(value)).orElseThrow(Exception::new);
但为了它的工作,ifPresent
将不得不返回Optional
,这将有点奇怪.这意味着你可以一个ifPresent
接一个地链接,对值进行多次操作.这可能是一个很好的设计,但它并不是创造者所Optional
采用的.
那是因为ifPresent
返回无效.它无法链接.你可以这样做:
Entryentry = borrowed.entrySet().stream() .filter(entry -> Duration.between(entry.getValue(), Instant.now()) .toMillis() > leaseTimeInMillis) .findFirst() .orElseThrow(ConnectionPoolException::new)); entry.getKey().close(); borrowed.remove(entry.getKey());
你在寻找什么会读得很好:
.findFirst().ifPresent(value -> use(value)).orElseThrow(Exception::new);
但为了它的工作,ifPresent
将不得不返回Optional
,这将有点奇怪.这意味着你可以一个ifPresent
接一个地链接,对值进行多次操作.这可能是一个很好的设计,但它并不是创造者所Optional
采用的.