我有一个流,想检查是否所有匹配过滤器.如果全部匹配,则返回true
.
但是,如果流是空的,我想回来false
.
我怎样才能做到这一点?
示例代码:
public boolean validate(Stream<Whatever> stream) {
// Problem: returns **true** if stream empty.
// How can **false** be returned if stream is empty?
return stream.allMatch(Whatever::someCheck);
}
Run Code Online (Sandbox Code Playgroud) 我是Java 8的新手.我无法理解下面这段代码中的错误.Collection<User>
如果它不是空的,那就是发送.但如果集合为空,则发送HttpStatus.NOT_FOUND
实体响应.
@RequestMapping(value = "/find/pks",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Collection<User>> getUsers(@RequestBody final Collection<String> pks)
{
return StreamSupport.stream(userRepository.findAll(pks).spliterator(), false)
.map(list -> new ResponseEntity<>(list , HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
Run Code Online (Sandbox Code Playgroud)
Eclipse在以下方面向我显示错误 .orElse
该
orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND))
类型的方法未定义Stream<ResponseEntity<User>>
我的基本接口方法如下所示
Iterable<T> findAll(Iterable<PK> pks);
Run Code Online (Sandbox Code Playgroud) 我想使用Stream.allMatch()
,但当false
流为空时我需要 a 。
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(testMethod(Stream.empty())); // <- expected false (but is true)
System.out.println(testMethod(Stream.of("match", "match"))); // <- expected true
System.out.println(testMethod(Stream.of("match", "no match"))); // <- expected false
}
private static boolean testMethod(Stream<String> stream) {
return stream.allMatch(text -> "match".equals(text));
}
Run Code Online (Sandbox Code Playgroud)
我不想用...
.toList()
,因为我想要Java 8 Streams 的短路如何工作?.reduce()
,因为Java 8 Streams 的短路如何工作?我想,我必须使用noMatch()
,但我没有得到正确工作的否定。
private static boolean testMethod(Stream<String> stream) {
// my guess, but the results are wrong …
Run Code Online (Sandbox Code Playgroud)