How can I get the last element of a stream or list in the following code?
Where data.careas is a List:
CArea f
If you need to get the last N number of elements. Closure can be used. The below code maintains an external queue of fixed size until, the stream reaches the end.
final Queue queue = new LinkedList<>();
final int N=5;
list.stream().peek((z) -> {
queue.offer(z);
if (queue.size() > N)
queue.poll();
}).count();
Another option could be to use reduce operation using identity as a Queue.
final int lastN=3;
Queue reduce1 = list.stream()
.reduce(
(Queue)new LinkedList(),
(m, n) -> {
m.offer(n);
if (m.size() > lastN)
m.poll();
return m;
}, (m, n) -> m);
System.out.println("reduce1 = " + reduce1);