0

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
harsha hegde
  • 17
  • 1
  • 2

3 Answers3

2

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();
      }
   });
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
1

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.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

Here's one way:

if(list.stream().filter(response -> (response.tokenExpiry<currentTimeInMillis).findAny().isPresent()) {
    throw new CustomExeption("message");
}
Prashant Pandey
  • 4,332
  • 3
  • 26
  • 44