简体   繁体   中英

How to throw exception from java streams after satisfying a filter condition

I have list of response from a rest WS. This list contains "Response" objects in which each object contains e field called "tokenExpiry". If any one of these token expiry is < currentTimeInMillis , then I have to throw an exception

Pseudo code something like this

list.stream().filter(response -> response.tokenExpiry < currentTimeInMillis) 

then throw new Exception .

Use filter for Responses response.tokenExpiry<currentTimeInMillis and findFirst to break stream after first match, then use ifPresent to throw exception

list.stream().filter(response->response.tokenExpiry<currentTimeInMillis).findFirst().ifPresent(s-> {
        throw new RuntimeException(s);
    });

Or you can also use anyMatch which returns boolean

boolean res = list.stream().anyMatch(response->response.tokenExpiry<currentTimeInMillis)
if(res) {
    throw new RuntimeException();
 }

Or simple forEach is also better choice

list.forEach(response-> {
     if(response.tokenExpiry<currentTimeInMillis) {
           throw new RuntimeException();
      }
   });

Java Streams have a specific method for checking whether any element of the stream matches a condition:

if (list.stream().anyMatch(r -> r.tokenExpiry < currentTimeInMillis)) {
    // throw your exception
}

This is a bit simpler and more efficient, but it doesn't provide you the actual value, which @Deadpool's find version does.

Here's one way:

if(list.stream().filter(response -> (response.tokenExpiry<currentTimeInMillis).findAny().isPresent()) {
    throw new CustomExeption("message");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM