How to check if Collection is empty using Java Stream


Saurabh Kumar

I am new to Java 8 and I am not able to understand the error in the following code. The idea is to send Collection<User>if it's not null. But if the collection is empty than send the HttpStatus.NOT_FOUNDentity 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 is showing me errors at the following points.orElse

method of this orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND))type is undefinedStream<ResponseEntity<User>>

My base interface method looks like this

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

You are confusing two things. The first task is to convert Iterableit to Collectionsomething you can indeed solve using the StreamAPI:

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

Note that this stream is stream Users , not a stream of lists. So you cannot listuse this stream to map a to other objects. This mapoperation maps each element in the stream to a new element.

Then you can use this list to createResponseEntity

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

You can combine these steps by creating a single Collectorstep that does this, although this doesn't offer any advantage, it's just 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) ));

Related


How to check if Collection is empty using Java Stream

Saurabh Kumar I am new to Java 8 and I am not able to understand the error in the following code. The idea is to send Collection<User>if it's not null. But if the collection is empty than send the HttpStatus.NOT_FOUNDentity response. @RequestMapping(value = "/

How to check if Collection is empty using Java Stream

Saurabh Kumar I am new to Java 8 and I am not able to understand the error in the following code. The idea is to send Collection<User>if it's not null. But if the collection is empty than send the HttpStatus.NOT_FOUNDentity response. @RequestMapping(value = "/

How to check if Collection is empty using Java Stream

Saurabh Kumar I am new to Java 8 and I am not able to understand the error in the following code. The idea is to send Collection<User>if it's not null. But if the collection is empty than send the HttpStatus.NOT_FOUNDentity response. @RequestMapping(value = "/

How to check if Collection is empty using Java Stream

Saurabh Kumar I am new to Java 8 and I am not able to understand the error in the following code. The idea is to send Collection<User>if it's not null. But if the collection is empty than send the HttpStatus.NOT_FOUNDentity response. @RequestMapping(value = "/

How to check if src stream is empty using Gulpjs?

Township I have a task to select and copy target environment related configuration files. var environment = process.env.NODE_ENV || (gulputil.env.environment || 'production'); process.env.NODE_ENV = environment; // copies ./src/configs/default-<enviro

How to check if Java 8 Stream is empty?

cephalopod StreamAs a non-terminal operation, how can I check if a is empty and throw an exception if it isn't ? Basically, I'm looking for something equivalent to the code below, but don't have that flow implemented in between. In particular, the check should

How to check if Java 8 Stream is empty?

cephalopod StreamAs a non-terminal operation, how can I check if a is empty and throw an exception if it isn't ? Basically, I'm looking for something equivalent to the code below, but don't have that flow implemented in between. In particular, the check should

LogicApp - How to check if a collection is empty using length

Greg In my JSON result I am trying to see if a particular object exists and if so what is the count. I am using lengthan expression but it seems to fail for me with the error: The template function 'lenth' is not defined or not valid. Here is my Get_Ticketobj

LogicApp - How to check if a collection is empty using length

Greg In my JSON result I am trying to see if a particular object exists and if so what is the count. I am using lengthan expression but it seems to fail for me with the error: The template function 'lenth' is not defined or not valid. Here is my Get_Ticketobj

LogicApp - How to check if a collection is empty using length

Greg In my JSON result I am trying to see if a particular object exists and if so what is the count. I am using lengthan expression but it seems to fail for me with the error: The template function 'lenth' is not defined or not valid. Here is my Get_Ticketobj

LogicApp - How to check if a collection is empty using length

Greg In my JSON result I am trying to see if a particular object exists and if so what is the count. I am using lengthan expression but it seems to fail for me with the error: The template function 'lenth' is not defined or not valid. Here is my Get_Ticketobj

LogicApp - How to check if a collection is empty using length

Greg In my JSON result I am trying to see if a particular object exists and if so what is the count. I am using lengthan expression but it seems to fail for me with the error: The template function 'lenth' is not defined or not valid. Here is my Get_Ticketobj

LogicApp - How to check if a collection is empty using length

Greg In my JSON result I am trying to see if a particular object exists and if so what is the count. I am using lengthan expression but it seems to fail for me with the error: The template function 'lenth' is not defined or not valid. Here is my Get_Ticketobj

How to check if Firestore collection is empty?

Edric I am using Angular and Angularfire2. I want to check if Firestore collection is empty. I'm making a todo app and I want to display an empty status container as part of a material guide . Here is my data structure: users/ userID/ todos/ // etc

How to check if map or collection is empty?

Zac Delventhal Using traditional objects in JavaScript, it's easy to check if it's null using :Object.keys const emptyObj = {}; console.log(Object.keys(emptyObj).length === 0); // true, i.e. "empty" const populatedObj = { foo: 'bar' }; console.log(Object.key

How to check if map or collection is empty?

Zac Delventhal Using traditional objects in JavaScript, it's easy to check if it's null using :Object.keys const emptyObj = {}; console.log(Object.keys(emptyObj).length === 0); // true, i.e. "empty" const populatedObj = { foo: 'bar' }; console.log(Object.key

How to check if map or collection is empty?

Zac Delventhal Using traditional objects in JavaScript, it's easy to check if it's null using :Object.keys const emptyObj = {}; console.log(Object.keys(emptyObj).length === 0); // true, i.e. "empty" const populatedObj = { foo: 'bar' }; console.log(Object.key

How to check if map or collection is empty?

Zac Delventhal Using traditional objects in JavaScript, it's easy to check if it's null using :Object.keys const emptyObj = {}; console.log(Object.keys(emptyObj).length === 0); // true, i.e. "empty" const populatedObj = { foo: 'bar' }; console.log(Object.key

How to check if map or collection is empty?

Zac Delventhal Using traditional objects in JavaScript, it's easy to check if it's null using :Object.keys const emptyObj = {}; console.log(Object.keys(emptyObj).length === 0); // true, i.e. "empty" const populatedObj = { foo: 'bar' }; console.log(Object.key

Java Lambda - Check if ArrayList to stream is empty

cut I have the following lambda expression which works fine if bonusScheduleDurationContainersnot empty . If empty, I get one NoSuchElementException. How to check in lambda expression? final List<ScheduleDurationContainer> bonusScheduleDurationContainers