I have a Stream of Lists of which I want to get the entry with the least elements. I could of course do something like
Stream<List<T>> s = ...
s.min((e1, e2) -> e1.size() - e2.size());
But in a case like this, we know a lower bound for the minimum, since the size is non-negative. Meaning the moment a List of size 0 is found, we could actually stop, instead of running through the rest of the list too. Can this be achieved in a decent way with Java Streams?
I would imagine it looking something like this, giving a comparator and a function which tells us when the current minimum is a global one:
s.boundedMin(
(e1, e2) -> e1.size() - e2.size(),
e -> e.size() == 0
)
I can't think of a way to implement this.
Of course I could just use an Iterable and use a loop with break-statement to get this, I just wondered if streams could get me there too.
Edit: To make it a bit clearer. The Stream might or might not contain Lists of size 0. My issue is that min() will run through the whole stream, even if it already found a list of size 0 (which is already as small as it can ever get). So, what I'm looking for is an implementation of min which does not need to scan through the whole stream, by providing a lower bound for the minimum.
Edit2: An equivalent iterative solution without streams would be
List<List<T>> s = ...
List<T> min = null;
for (List<T> l : s) {
if (min == null || min.size() > l.size())
min = l;
if (min.size() == 0) {
break;
}
}
>`? there are at least two issues here : 1) your Lists might not have a trivial `size` 2) the stream might be lazily computed - making your requirement entirely valid; but again _only_ if you are stuck with a `Stream
– Eugene Sep 10 '19 at 15:07>`, otherwise you already know what to do...