在Java 8中,您可以使用方法引用来过滤流,例如:
Stream<String> s = ...;
long emptyStrings = s.filter(String::isEmpty).count();
Run Code Online (Sandbox Code Playgroud)
有没有办法创建一个方法引用,它是对现有方法的否定,即:
long nonEmptyStrings = s.filter(not(String::isEmpty)).count();
Run Code Online (Sandbox Code Playgroud)
我可以创建not如下所示的方法,但我想知道JDK是否提供了类似的东西.
static <T> Predicate<T> not(Predicate<T> p) { return o -> !p.test(o); }
Run Code Online (Sandbox Code Playgroud) 在Spring中,RestController我RequestBody只需通过将相应的方法参数注释为@Valid或者进行输入验证@Validated.其他一些验证只能在对传入数据进行一些处理后才能执行.我的问题是,我应该使用什么类型的异常,以便它类似于@Valid注释抛出的异常,以及如何从验证结果中构造此异常.这是一个例子:
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> createOrder(@RequestBody @Validated(InputChecks.class) Order order) {
// Some processing of the Order goes here
Set<ConstraintViolation<Order>> violations = validator.validate(order, FinalChecks.class);
// What to do now with the validation errors?
orders.put(order);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ServletUriComponentsBuilder.fromCurrentRequest().path("/" + order.getId()).build().toUri());
return new ResponseEntity<>(null, headers, HttpStatus.CREATED);
}
Run Code Online (Sandbox Code Playgroud)