满足滤波器条件后,如何从Java流中抛出异常



我有rest ws的响应列表。此列表包含"响应"对象,其中每个对象包含称为" Tokenexpriry"的E字段。如果这些代币中有任何一个是<CurrentTimeInmillis,然后我必须抛出一个异常

伪代码类似这样

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

然后投掷new Exception

使用 filter进行响应response.tokenExpiry<currentTimeInMillisfindFirst在第一次匹配后打破流,然后使用ifPresent投掷异常

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

或者您也可以使用返回boolean

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

或简单的forEach也是更好的选择

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

java流具有检查流中任何元素是否匹配条件的特定方法:

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

这更简单,更有效,但并不能为您提供实际值, @DeadPool的find版本。

这是一种方法:

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

最新更新