Monday, November 18, 2024
Google search engine
HomeLanguagesJavaFind the last element of a Stream in Java

Find the last element of a Stream in Java

Given a stream containing some elements, the task is to get the last element of the Stream in Java.

Example:

Input: Stream={“Geek_First”, “Geek_2”, “Geek_3”, “Geek_4”, “Geek_Last”}
Output: Geek_Last

Input: Stream={1, 2, 3, 4, 5, 6, 7}
Output: 7

There are many methods to find last elements in a Stream:

  1. Using Stream.reduce() Method: The reduce method works on two elements in the stream and returns the element as per the required condition. Therefore this method can be used to reduce the stream so that it contains only the last element.

    Approach:

    • Get the stream of elements in which the first element is to be returned.
    • To get the last element, you can use the reduce() method to ignore the first element, repeatedly, till there is no first element.
      Stream.reduce((first, second) -> second)
      
    • This reduces the set of elements in a Stream to a single element, which is last.
    • Hence the only single element will be remain in the stream which is the last element.

    Below is the implementation of the above approach:
    Example:




    // Java program to find last
    // element of a Stream in Java
      
    import java.util.*;
    import java.util.stream.*;
      
    public class GFG {
      
        // Function to find the
        // last_elements in a Stream
        public static <T> T
        lastElementInStream(Stream<T> stream)
        {
            T last_element
                = stream
      
                      // reduce() method reduces the Stream
                      // to a single element, which is last.
                      .reduce((first, second) -> second)
      
                      // if stream is empty
                      // null is returned
                      .orElse(null);
      
            return last_element;
        }
      
        // Driver code
        public static void main(String[] args)
        {
      
            Stream<String> stream
                = Stream.of("Geek_First", "Geek_2",
                            "Geek_3", "Geek_4",
                            "Geek_Last");
      
            // Print the last element of a Stream
            System.out.println(
                "Last Element: "
                + lastElementInStream(stream));
        }
    }

    
    
    Output:

    Last Element: Geek_Last
    
  2. Using Stream skip() Method: The skip() method returns a stream after removing first N elements. Therefore this method can be used to skip the elements except the last one.

    Approach:

    • Get the stream of elements in which the last element is to be returned.
    • To get the last element, you can use the skip() method along with count() method.
      Stream.skip(stream.count()-1)
    • This returns a stream after removing first size()-1 elements, which results in single element stream.
    • This method is followed by findFirst() method, which return the first element which is actually a last element of original stream.

    Below is the implementation of the above approach:
    Example:




    // Java program to find last
    // element of a Stream in Java
      
    import java.util.*;
    import java.util.stream.*;
      
    public class GFG {
      
        // Function to find the
        // last_elements in a Stream
        public static <T> T
        lastElementInStream(Stream<T> stream, int N)
        {
      
            T last_element
                = stream
      
                      // This returns a stream after
                      // removing first N-1 elements
                      // resultant stream will contain
                      // only single element
                      .skip(N - 1)
      
                      // findFirst() method return
                      // the first element of
                      // newly generated stream
                      .findFirst()
      
                      // if stream is empty
                      // null is returned
                      .orElse(null);
      
            return last_element;
        }
      
        // Driver code
        public static void main(String[] args)
        {
      
            Stream<String> stream
                = Stream.of("Geek_First", "Geek_2",
                            "Geek_3", "Geek_4",
                            "Geek_Last");
      
            int N = 5;
      
            // Print the last element of a Stream
            System.out.println(
                "Last Element: "
                + lastElementInStream(stream, N));
        }
    }

    
    
    Output:

    Last Element: Geek_Last
    
  3. Find the first element of the reversed stream:

    Approach:

    • Get the stream of elements in which the first element is to be returned.
    • To get the first element, you have to first reverse the stream. Reversing can be done as:
      stream.sorted(Collections.reverseOrder())
      
    • This method is followed by findFirst() method, which return the first element of reverse stream.
    • Hence the first element of original stream is obtained.

    Below is the implementation of the above approach:
    Example:




    // Java program to find last
    // element of a Stream in Java
      
    import java.util.*;
    import java.util.stream.*;
      
    public class GFG {
      
        // Function to find the
        // last_elements in a Stream
        public static <T> T
        lastElementInStream(Stream<T> stream)
        {
            T last_element
                = stream
      
                      // sorted(Collections.reverseOrder())
                      // is used to reverse the element of the stream
                      .sorted(Collections.reverseOrder())
      
                      // findFirst() method return
                      // the first element of reversed stream
                      // which is the last element of the stream
                      .findFirst()
      
                      // if stream is empty
                      // null is returned
                      .orElse(null);
      
            return last_element;
        }
      
        // Driver code
        public static void main(String[] args)
        {
      
            Stream<String> stream
                = Stream.of("Geek_First", "Geek_2",
                            "Geek_3", "Geek_4",
                            "Geek_Last");
      
            // Print the last element of a Stream
            System.out.println(
                "Last Element: "
                + lastElementInStream(stream));
        }
    }

    
    
    Output:

    Last Element: Geek_Last
    
RELATED ARTICLES

Most Popular

Recent Comments