java 如何使用java Stream检查Collection是否为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30631650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:24:53  来源:igfitidea点击:

How to check if Collection is not empty using java Stream

javalambdajava-8java-stream

提问by Saurabh Kumar

I am new to Java 8. I am not able to understand what is wrong in the following piece of code. The idea is to sent Collection<User>if its not empty. But if the collection is empty than sent HttpStatus.NOT_FOUNDEntity response.

我是 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));
}

Eclipse shows me error in the following point .orElse

Eclipse 显示以下错误 .orElse

The method orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND))is undefined for the type Stream<ResponseEntity<User>>

orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND))类型的方法未定义Stream<ResponseEntity<User>>

My base interface method looks like following

我的基本接口方法如下所示

Iterable<T> findAll(Iterable<PK> pks);

采纳答案by Holger

You are mixing two things up. The first task is to convert the Iterableto a Collectionwhich you can indeed solve using the StreamAPI:

你把两件事混在一起了。第一个任务是将转换IterableCollection你的确可以解决使用StreamAPI:

Collection<User> list=
    StreamSupport.stream(userRepository.findAll(pks).spliterator(), false)
   .collect(Collectors.toList());

Note that this stream is a stream of Users, not a stream of lists. Therefore you can't map a listto something else with this stream. The mapoperation will map each elementof the stream to a new element.

请注意,此流是sUser,而不是列表流。因此,您无法list使用此流将 a 映射到其他内容。该map操作会将流的每个元素映射到一个新元素。

Then you can use this list to create the ResponseEntity

然后你可以使用这个列表来创建 ResponseEntity

return list.isEmpty()? new ResponseEntity<>(HttpStatus.NOT_FOUND):
                       new ResponseEntity<>(list, HttpStatus.OK);

You can combine these steps by creating a Collectorperforming this steps though this does not provide any advantage, it's only a matter of style:

您可以通过创建Collector执行这些步骤来组合这些步骤,尽管这不会提供任何优势,这只是风格问题:

ResponseEntity<User> responseEntity=
    StreamSupport.stream(userRepository.findAll(pks).spliterator(), false)
   .collect(Collectors.collectingAndThen(Collectors.toList(),
      list -> list.isEmpty()? new ResponseEntity<>(HttpStatus.NOT_FOUND):
                              new ResponseEntity<>(list, HttpStatus.OK) ));

回答by Bohemian

It's not necessary, and often a mistake, to cram everything into one line. In this case, you can't - there's no such API for your intention.

将所有内容都塞进一行是没有必要的,而且常常是错误的。在这种情况下,您不能 - 没有适合您的 API。

Keep it simple:

把事情简单化:

Collection<User> list = <your stream code that gets a list>;
if (list.isEmpty())
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(list, HttpStatus.OK);

but if you absolutely must:

但如果你绝对必须

return <your code>.map(list -> new ResponseEntity<>(list, list.isEmpty() ? HttpStatus.NOT_FOUND : HttpStatus.OK));

回答by the8472

That depends on your terminal operation of the stream, remember that a stream can only be consumed once.

这取决于你对流的终端操作,记住一个流只能被消费一次。

  • Is it a grouping by/statistics operation? Then you'll get a 0 count or an empty map of groups.
  • If it collects into a list then it's an empty list.
  • If it's one of the methods that returns an Optional(such as findAny) then you can use the optional's null-checking methods.
  • 它是按/统计操作分组吗?然后你会得到一个 0 计数或一个空的组图。
  • 如果它收集到一个列表中,那么它就是一个空列表。
  • 如果它是返回一个Optional(例如findAny)的方法之一,那么您可以使用可选的空检查方法。