在Java 8中,我们可以使用reduce
或skip
获取Stream的最后一个元素。
1.
package ;
import ;
import ;
public class Java8Example1 {
public static void main(String[] args) {
List<String> list = ("node", "java", "c++", "react", "javascript");
String result = ().reduce((first, second) -> second).orElse("no last element");
(result);
}
}
输出量
javascript
2.
package ;
import ;
import ;
public class Java8Example2 {
public static void main(String[] args) {
List<String> list = ("node", "java", "c++", "react", "javascript");
// get last element from a list
String result = (() - 1);
(result);
// get last element from a stream, via skip
String result2 = ().skip(() - 1).findFirst().orElse("no last element");
(result2);
}
}
输出量
javascript
javascript
参考文献
流JavaDoc
Java –获取列表的最后一个元素
Java 8 Stream findFirst()和findAny()
Java 8 ()示例
翻译自: /java8/java-8-get-the-last-element-of-a-stream/
推荐阅读--