Java stream orElseThrow

I want to convert a piece of code from a connection pool project that I've been trying to use streams

The original code is

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

I already understand that

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;

The above can be compiled, but the moment I add orelsethrow after ifpresent, I get the following

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

Solution

That's because ifpresent returns void It cannot be linked You can do this:

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

What are you looking for to read well:

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

But in order to work, ifpresent must return optional, which is a little strange This means that you can link one ifpresent to another and perform multiple operations on the value This may be a good design, but it was not adopted by the creators of optional

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>