加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java流.orElseThrow

发布时间:2020-12-15 05:13:28 所属栏目:Java 来源:网络整理
导读:我想从我一直在努力使用流的连接池项目中转换一段代码 原始代码是 for (Map.EntryJdbConnection,Instant entry : borrowed.entrySet()) { Instant leaseTime = entry.getValue(); JdbConnection jdbConnection = entry.getKey(); Duration timeElapsed = Dur
我想从我一直在努力使用流的连接池项目中转换一段代码

原始代码是

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");

我已经明白了这一点

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;

以上可以编译但是我在IfPresent之后添加orElseThrow的那一刻我得到以下内容

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

解决方法

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

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());

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

.findFirst().ifPresent(value -> use(value)).orElseThrow(Exception::new);

但是为了工作,ifPresent必须返回Optional,这有点奇怪.这意味着您可以将一个ifPresent链接到另一个,对该值执行多个操作.这可能是一个很好的设计,但它不是Optional的创造者所采用的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读