如何在满足筛选条件后从java流引发异常

如何在满足筛选条件后从java流引发异常,java,exception,java-stream,Java,Exception,Java Stream,我有来自rest WS的响应列表。此列表包含“响应”对象,其中每个对象都包含一个名为“令牌到期”的字段。如果这些令牌到期时间中的任何一个小于currentTimeInMillis,那么我必须抛出一个异常 list.stream().filter(response->response.tokenExpiry<currentTimeInMillis).findFirst().ifPresent(s-> { throw new RuntimeException(s);

我有来自rest WS的响应列表。此列表包含“响应”对象,其中每个对象都包含一个名为“令牌到期”的字段。如果这些令牌到期时间中的任何一个小于currentTimeInMillis,那么我必须抛出一个异常

list.stream().filter(response->response.tokenExpiry<currentTimeInMillis).findFirst().ifPresent(s-> {
        throw new RuntimeException(s);
    });
类似这样的伪代码

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

然后抛出
新异常

对响应使用
过滤器
{
如果(response.tokenExpiryJava Streams有一个特定的方法来检查流的任何元素是否与条件匹配:

if (list.stream().anyMatch(r -> r.tokenExpiry < currentTimeInMillis)) {
    // throw your exception
}
if(list.stream(){
//抛出你的异常
}
这有点简单,效率也更高,但它并没有提供@Deadpool的
find
版本提供的实际值。

这里有一种方法:

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

if(list.stream().filter(response->)(response.tokenexpireydon)不要忘记
anyMatch()
。anyMatch将返回布尔右键,这不是可选的@chrylisCorrect,但如果您不需要匹配元素,可以消除绒毛。我将记录答案中的差异。此外,
findAny
几乎总是足够好,有时效率更高。@GhostCat不是重复的;是XY。
if (list.stream().anyMatch(r -> r.tokenExpiry < currentTimeInMillis)) {
    // throw your exception
}
if(list.stream().filter(response -> (response.tokenExpiry<currentTimeInMillis).findAny().isPresent()) {
    throw new CustomExeption("message");
}