🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Streams in Java 8 are designed for processing collections in a functional way, but they do not directly provide a method to retrieve the last element. This is because streams are processed in a forward-only manner. However, we can still find the last element of a stream using a few different approaches, depending on whether the stream is ordered or unordered.
In this guide, we will explore two methods to get the last element of a stream: one for finite, ordered streams and another using a reduction operation.
Solution Steps
- Convert to List and Access Last Element: Convert the stream to a list and get the last element.
- Use Reduce Operation: Use the
reduce()method to keep track of the last processed element.
Java Program
Method 1: Convert Stream to List
import java.util.Arrays;
import java.util.List;
public class LastElementOfStream {
public static void main(String[] args) {
// Step 1: Define a list and create a Stream
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
// Step 2: Convert the Stream to a List and get the last element
Integer lastElement = numbers.stream()
.reduce((first, second) -> second) // Reduce to get last element
.orElse(null); // Handle case where stream is empty
// Step 3: Display the last element
System.out.println("Last element: " + lastElement);
}
}
Output
Last element: 7
Explanation
- Step 1: We define a list of integers, which serves as the source for the stream.
- Step 2: The
reduce()method is used to iterate over the stream. The lambda expression(first, second) -> secondkeeps updating the value with the current element until the last element is reached.- If the stream is empty,
orElse(null)will returnnullas a fallback.
- If the stream is empty,
- Step 3: The last element is printed to the console.
Method 2: Convert Stream to List and Get Last Element
Another approach is to convert the stream into a List and then access the last element directly.
Example
import java.util.Arrays;
import java.util.List;
public class LastElementOfStreamUsingList {
public static void main(String[] args) {
// Step 1: Define a list and create a Stream
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7);
// Step 2: Convert the Stream to a List
List<Integer> numberList = numbers.stream().toList();
// Step 3: Get the last element from the list
Integer lastElement = numberList.isEmpty() ? null : numberList.get(numberList.size() - 1);
// Step 4: Display the last element
System.out.println("Last element: " + lastElement);
}
}
Output
Last element: 7
Explanation
- Step 1: We start by defining the list, which will be converted to a stream.
- Step 2: The
stream().toList()method converts the stream back into a list. - Step 3: We access the last element of the list using
numberList.get(numberList.size() - 1)and check if the list is empty. - Step 4: The last element is printed.
Conclusion
In Java 8, although there is no direct method to retrieve the last element of a stream, we can achieve this using either the reduce() method or by converting the stream into a list and accessing the last element. Both approaches are efficient for different scenarios, depending on the size of the stream and the nature of the data.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment