BAEL-833: How to get last element of a Stream in Java? (#1930)

* Different Types of Bean Injection in Spring

* Fixed code formatting and test names for "Different Types of Bean Injection in Spring"

* BAEL-833: How to get last element of a Stream in Java?

* BAEL-833: Updated based on review from editor
This commit is contained in:
Syed Ali Raza
2017-05-28 15:07:15 +05:00
committed by Grzegorz Piwowarek
parent 99c7a91587
commit 8c8c01ebbb
13 changed files with 306 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
package com.baeldung.stream;
import java.util.List;
import java.util.stream.Stream;
public class StreamApi {
public String getLastElementUsingReduce(List<String> valueList) {
Stream<String> stream = valueList.stream();
return stream.reduce((first, second) -> second).orElse(null);
}
public Integer getInfiniteStreamLastElementUsingReduce() {
Stream<Integer> stream = Stream.iterate(0, i -> i + 1);
return stream.limit(20).reduce((first, second) -> second).orElse(null);
}
public String getLastElementUsingSkip(List<String> valueList) {
long count = valueList.stream().count();
Stream<String> stream = valueList.stream();
return stream.skip(count - 1).findFirst().orElse(null);
}
}