There is no method called Stream # isEmpty
, so I don't know how to write it best, so I write it in Qiita.
First of all, in normal times, I would write as follows.
list.stream()
.anyMatch(Condition lambda expression or method reference);
But this time, how should I write if I just want to make a judgment like List # isEmpty
for Stream
? It is a story.
For example, I just want to judge whether there is a result in Stream
that was returned by throwing a query in Doma2. May use.
As a result, I don't know the answer which is the best, but I write the pattern I thought about.
It may be a little scary at first glance.
boolean notEmpty = stream()
.anyMatch(e -> true);
System.out.println(notEmpty);
Iterator#hasNext
Impression that you do not know what you want to do at a glance without explanatory variables.
boolean notEmpty = stream()
.iterator()
.hasNext();
System.out.println(notEmpty);
Optional#isPresent
Hmm.
boolean notEmpty = stream()
.findAny()
.isPresent();
System.out.println(notEmpty);
count
NG because there is a lot of waste.
boolean notEmpty = stream()
.count() > 0;
System.out.println(notEmpty);
This is still better.
//Still better
boolean notEmpty = stream()
.limit(1)
.count() > 0;
System.out.println(notEmpty);
toList
This is also wasteful, so NG.
boolean notEmpty = !stream()
.collect(Collectors.toList())
.isEmpty();
System.out.println(notEmpty);
Isn't the pattern of ʻIterator # hasNext good for efficiency? (Especially if used with Doma2) If I was in that scene, I would write it with ʻany Match (e-> true)
, which seems to be the easiest without thinking about anything.
Recommended Posts