A java stream is a sequence of elements and at some time you might be required to know the last stream element.
There are three methods of getting the last element of a stream.
[the_ad id=”651″]
Method 1: Using reduce method
reduce method of a stream takes a parameter of type java.util.function.BinaryOperator which is a functional interface having a single method apply.
This method accepts two arguments and returns a result.
Thus, we can supply a Lambda expression to reduce matching the signature of apply .
This lamdba expression takes two elements and just returns the second element, then at the end of stream we will be getting the last element.
Example,
List<Integer> list = Arrays.asList(new Integer[] {1,2,3,55,67,34,20});
Integer lastElement = list.stream().
reduce((first, second) -> second).
orElse(null);
This method will return null if the stream is empty.
[the_ad id=”3385″]
Method 2: Using skip
skip method of java.util.stream.Stream accepts a numeric value and skip the number of stream elements equal to this value.
It returns a stream with remaining elements after skipping those elements.
Thus, if skip is supplied a number which is one less than the total number of elements in the stream, then the resulting stream will have the last element. Example,
List<Integer> list = Arrays.asList(new Integer[] {1,2,3,55,67,34,20});
// total number of stream elements
long count = list.stream().count();
// element at count -1 position
Integer last = list.stream().
skip(count - 1).
findFirst().
get();
For getting the total number of stream elements, count() method is used.
Also, skip() returns a stream, use its findFirst() method to get the first stream element.
findFirst() returns an Optional object, use its get() method to get the value of element.
[the_ad id=”644″]
Method 3: Using guava library
Guava library has a class com.google.common.collect.Streams which has a findLast() method.
This method takes a stream as argument and returns its last element. Example,
List<Integer> list = Arrays.asList(new Integer[] {1,2,3,55,67,34,20});
Optional<Integer> lastElement = com.google.common.collect.Streams.findLast(list.stream());
Integer last = lastElement.get();
findLast() method returns an Optional object, hence you need to call its get() method to get the value of last element.
[AdSense-A]
These are the three ways in which last element of stream can be retrieved. Hit the clap if the article was useful
Previous Article
Next Article