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.

3
Leave a Reply

avatar
3 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

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

Jason
Guest

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.

Jason
Guest

Here’s one way:

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