lambda - How to check if Collection is not empty using java Stream -
i new java 8. not able understand wrong in following piece of code. idea sent collection<user>
if not empty. if collection empty 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 shows me error in following point .orelse
the method
orelse(new responseentity<>(httpstatus.not_found))
undefined typestream<responseentity<user>>
my base interface method looks following
iterable<t> findall(iterable<pk> pks);
you mixing 2 things up. first task convert iterable
collection
can indeed solve using stream
api:
collection<user> list= streamsupport.stream(userrepository.findall(pks).spliterator(), false) .collect(collectors.tolist());
note stream stream of user
s, not stream of lists. therefore can’t map list
else stream. map
operation map each element of stream new element.
then can use list create responseentity
return list.isempty()? new responseentity<>(httpstatus.not_found): new responseentity<>(list, httpstatus.ok);
you can combine these steps creating collector
performing steps though not provide advantage, it’s 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) ));
Comments
Post a Comment