如何使用Java Stream检查Collection是否为空 [英] How to check if Collection is not empty using java Stream

查看:2037
本文介绍了如何使用Java Stream检查Collection是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java 8的新手.我无法理解以下代码中的错误.这个想法是发送Collection<User>如果它不为空.但是,如果集合为空,则发送的是HttpStatus.NOT_FOUND实体响应.

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_FOUND Entity response.

@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在以下几点向我显示错误.orElse

Eclipse shows me error in the following point .orElse

对于类型Stream<ResponseEntity<User>>

我的基本接口方法如下

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

推荐答案

您正在混淆两件事.第一个任务是将Iterable转换为Collection,您确实可以使用Stream API解决此问题:

You are mixing two things up. The first task is to convert the Iterable to a Collection which you can indeed solve using the Stream API:

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

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

Note that this stream is a stream of Users, not a stream of lists. Therefore you can’t map a list to something else with this stream. The map operation will map each element of the stream to a new element.

然后您可以使用此列表创建ResponseEntity

Then you can use this list to create the ResponseEntity

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

您可以通过创建执行以下步骤的Collector来组合这些步骤,尽管这并没有任何好处,这只是样式问题:

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

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) ));

这篇关于如何使用Java Stream检查Collection是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆