Wednesday, September 11, 2019

Java 8: How to Get the Last Element of a Stream in Java?

$type=blogging

1. Introduction

[post_ads]

in this tutorial, We will be looking at different ways to get the last element of a Stream in Java 8.

When we work with Stream then we have to go through one by one element of Stream. But, if we want to get directly last value and ignore the remaining preceding elements.

here are the possible ways to retrieve only the last value from the stream.

2. Using reduce() method

[lock]
reduce() method is part of the Stream API and we have to pass the lambda expression with two arguments. [/lock]

Syntax:


Optional reduce​(BinaryOperator accumulator)


FI BinaryOperator is declared as below.

@FunctionalInterface
public interface BinaryOperator
extends BiFunction

Example using Reduce API:

package com.java.w3schools.blog.java8.stream;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class StreamLastElement {

 public static void main(String[] args) {

  List values = new ArrayList<>();
  values.add("First");
  values.add("Second");
  values.add("Third");
  values.add("Fourth");
  values.add("Last");

  Optional lastOptional = values.stream().reduce((str1, str2) -> str2);
  String lastValue = lastOptional.get();
  System.out.println("last value using reduce api: " + lastValue);

 }

}

reduce() method takes BiFunction functional interface as an argument.

Output:

last value using reduce api: Last

Optional API methods

3. Using skip() method

[post_ads]
Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned.

Syntax:

Stream skip​(long n)

Where n is the number of elements to be ignored from Stream.

Example using skip API:

  List fruits = new ArrayList<>();
  fruits.add("Banana");
  fruits.add("Apple");
  fruits.add("Kiwi");
  fruits.add("Sapota");
  fruits.add("BlueBerry");

  long noOfValues = fruits.stream().count();

  Stream skippedStream = fruits.stream().skip(noOfValues - 1);
  Optional lastFruit = skippedStream.findFirst();
  String lastFruitFromList = lastFruit.get();
  System.out.println("Last fruit from the list : " + lastFruitFromList);

Output:


Last fruit from the list : BlueBerry

if we pass n value as negative then it throws the below IllegalArgumnetException.

Exception in thread "main" java.lang.IllegalArgumentException: -1

4. Using Guava Streams API


Guava has a dedicated method in Streams class to get directly find the last element from Stream.

Syntax:

public static  Optional findLast(Stream stream)

As well as the above method it has a dedicated method for each data type.


public static OptionalInt findLast(IntStream stream)
public static OptionalLong findLast(LongStream stream)
public static OptionalDouble findLast(DoubleStream stream)

Returns the last element of the specified stream, or Optional.empty() if the stream is empty.

Example:

Stream stream = fruits.stream();
Optional lastItem = Streams.findLast(stream);


This is equal to the reduce() method.

5. Conclusion


In this article, We've seen the possible ways to find the last element from the Stream in java 8.

All the approaches have shown work for infinite streams as well.

As usual, the code is shown in this article is over GitHub.

6. References


Java 8 Functional Interfaces
reduce() method
skip() method
Guava Streams API
StackOverFlow

No comments:

Post a Comment