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
@@ -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);
}
}
@@ -0,0 +1,43 @@
package com.baeldung.stream;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class StreamApiTest {
private StreamApi streamApi = new StreamApi();
@Test
public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() {
List<String> valueList = new ArrayList<String>();
valueList.add("Joe");
valueList.add("John");
valueList.add("Sean");
String last = streamApi.getLastElementUsingReduce(valueList);
assertEquals("Sean", last);
}
@Test
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
Integer last = streamApi.getInfiniteStreamLastElementUsingReduce();
assertEquals(new Integer(19), last);
}
@Test
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
List<String> valueList = new ArrayList<String>();
valueList.add("Joe");
valueList.add("John");
valueList.add("Sean");
String last = streamApi.getLastElementUsingSkip(valueList);
assertEquals("Sean", last);
}
}