java – Get the last element of Stream / List in a row

How can I get the last element of a stream or list in the following code?

Where is it data.careas It’s a List:

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 item, with a certain filterit is not difficult.

However, getting the last item in a row is a real pain:

  • Seems like I can’t get it directly from a Stream. (It would only make sense for finite flows)
  • It also seems like you can’t get things like first() And last() from the interface Listwhich is really a nuisance.

I don’t see any arguments for not providing a method first() And last() in the interface Listsince the elements it contains are ordered and furthermore the size is known.

But according to 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, this implies the use of a indexOf on each item, which you most likely don’t want as it can affect performance.

Leave a comment