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()
and last()
from the List
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…