How can I get the last element of a stream or list in the following code?
Where data.careas
is a List<CArea>
:
CArea first = data.careas.stream()
.filter(c -> c.bbox.orientationHorizontal).findFirst().get();
CArea last = data.careas.stream()
.filter(c -> c.bbox.orientationHorizontal)
.collect(Collectors.toList()).; //how to?
As you can see getting the first element, with a certain filter
, is not hard.
However getting the last element in a one-liner is a real pain:
- It seems I cannot obtain it directly from a
Stream
. (It would only make sense for finite streams) - It also seems that you cannot get things like
first()
andlast()
from theList
interface, which is really a pain.
I do not see any argument for not providing a first()
and last()
method in the List
interface, as the elements in there, are ordered, and moreover the size is known.
But as per the original answer: How to get the last element of a finite Stream
?
Personally, this is the closest I could get:
int lastIndex = data.careas.stream()
.filter(c -> c.bbox.orientationHorizontal)
.mapToInt(c -> data.careas.indexOf(c)).max().getAsInt();
CArea last = data.careas.get(lastIndex);
However it does involve, using an indexOf
on every element, which is most likely not you generally want as it can impair performance.
Iterables.getLast
which takes Iterable but is optimized to work withList
. A pet peeve is that it doesn't havegetFirst
. TheStream
API in general is horribly anal, omitting lots of convenience methods. C#'s LINQ, by constrast, is happy to provide.Last()
and even.Last(Func<T,Boolean> predicate)
, even though it supports infinite Enumerables too. – CognizanceStream
API is not fully comparable toLINQ
since both done in a very different paradigm. It is not worse or better it is just different. And definitely some methods are absent not because oracle devs are incompetent or mean :) – Padova