<String> 使用流检查列表是否包含列表中的所有元素<Object>



我有两个列表:

List<String> authorizedList ; // ["11","22","33"]
List<MySerial> serials; // [Myserial1,Myserial2,Myserial3] => 

MySerial是有两个参数的对象,MySerial (String serial, String name)

我想检查是否所有串行从serials是在authorizedList使用流,但我是新的使用它。

if (!serials.stream().map(MySerial::getSerial).anyMatch(authorizedList::equals)) {
throw new UnauthorizedException();
}

但是它总是抛出异常。

authorizedList::equals改为authorizedList::contains

也可以将if语句从anyMatch反转到allMatch

。在这些建议之后,你应该有:

if (!serials.stream().map(MySerial::getSerial).allMatch(authorizedList::contains)) {
throw new UnauthorizedException();
}

最新更新