赞
踩
在Java 8中,我们可以使用reduce
或skip
获取Stream的最后一个元素。
Java8Example1.java
- package com.mkyong;
-
- import java.util.Arrays;
- import java.util.List;
-
- public class Java8Example1 {
-
- public static void main(String[] args) {
-
- List<String> list = Arrays.asList("node", "java", "c++", "react", "javascript");
-
- String result = list.stream().reduce((first, second) -> second).orElse("no last element");
-
- System.out.println(result);
-
- }
-
- }
输出量
javascript
Java8Example2.java
- package com.mkyong;
-
- import java.util.Arrays;
- import java.util.List;
-
- public class Java8Example2 {
-
- public static void main(String[] args) {
-
- List<String> list = Arrays.asList("node", "java", "c++", "react", "javascript");
-
- // get last element from a list
- String result = list.get(list.size() - 1);
-
- System.out.println(result);
-
- // get last element from a stream, via skip
- String result2 = list.stream().skip(list.size() - 1).findFirst().orElse("no last element");
-
- System.out.println(result2);
- }
-
- }
输出量
- javascript
- javascript
流JavaDoc
Java –获取列表的最后一个元素
Java 8 Stream findFirst()和findAny()
Java 8 Stream.reduce()示例
翻译自: https://mkyong.com/java8/java-8-get-the-last-element-of-a-stream/
推荐阅读--
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。