获取流的最后一个元素的最有效方法 [英] Most efficient way to get the last element of a stream

查看:67
本文介绍了获取流的最后一个元素的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Stream没有 last()方法:

Stream doesn't have a last() method:

Stream<T> stream;
T last = stream.last(); // No such method

获得最后一个元素的最优雅和/或最有效的方法是什么(或者null为空流?

What's the most elegant and/or efficient way to get the last element (or null for an empty Stream)?

推荐答案

执行简化返回当前值的缩减:

Do a reduction that simply returns the current value:

Stream<T> stream;
T last = stream.reduce((a, b) -> b).orElse(null);

这篇关于获取流的最后一个元素的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆