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:
committed by
Grzegorz Piwowarek
parent
99c7a91587
commit
8c8c01ebbb
24
core-java/src/main/java/com/baeldung/stream/StreamApi.java
Normal file
24
core-java/src/main/java/com/baeldung/stream/StreamApi.java
Normal 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);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user