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
进一步阅读: Java 8 Stream.reduce()示例
2. Stream.skip
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
转自:https://www.cnblogs.com/c68ychen/p/14208931.html
示例List
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
1、通过Stream()来获取
如果过滤器的计算结果为true,则检索该元素,否则返回最后一个元素。
int value = list.stream().filter(x -> x == 2)
.findFirst()
.orElse(list.get(list.size() - 1));
列表为空,则可以返回默认值,例如-1。
int value = list.stream().filter(x -> x == 2)
.findFirst()
.orElse(list.isEmpty() ? -1 : list.get(list.size() - 1));
2、通过for循环来实现
public static <T> T getFirstMatchingOrLast(List<? extends T> source, Predicate<? super T> predicate){
// handle empty case
if(source.isEmpty()){
return null;
for(T t : source){
if(predicate.test(t)){
return t;
return source.get(source.size() -1);
可以这样调用:
Integer match = getFirstMatchingOrLast(ints, i -> i == 7);
转自:https://www.cjavapy.com/article/188/