🎓 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
The collectingAndThen() method in Java, part of the java.util.stream.Collectors class, is used to perform a collection operation and then apply a finishing transformation to the result. This method is useful when you need to modify the result of a collection operation before using it.
Table of Contents
- Introduction
collectingAndThen()Method Syntax- Understanding
collectingAndThen() - Examples
- Basic Usage
- Using
collectingAndThen()for Custom Transformations
- Real-World Use Case
- Conclusion
Introduction
The collectingAndThen() method returns a Collector that performs a given reduction operation and then applies an additional finishing transformation. This method is particularly useful when you want to transform the result of a collection operation into another form.
collectingAndThen() Method Syntax
The syntax for the collectingAndThen() method is as follows:
public static <T, A, R, RR> Collector<T, A, RR> collectingAndThen(Collector<T, A, R> downstream, Function<R, RR> finisher)
Parameters:
downstream: ACollectorthat performs the reduction operation.finisher: A function that transforms the result of the reduction operation.
Returns:
- A
Collectorthat performs the reduction operation and applies a finishing transformation.
Throws:
- This method does not throw any exceptions.
Understanding collectingAndThen()
The collectingAndThen() method allows you to first collect the elements of a stream using a specified Collector and then apply a transformation to the collected result. This is useful in scenarios where you need to post-process the result of a collection operation.
Examples
Basic Usage
To demonstrate the basic usage of collectingAndThen(), we will collect a list of strings and convert the resulting list to an unmodifiable list.
Example
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
import java.util.stream.Collectors;
public class CollectingAndThenExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry");
// Collect the elements into an unmodifiable list
List<String> unmodifiableList = words.stream()
.collect(Collectors.collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
));
System.out.println("Unmodifiable List: " + unmodifiableList);
// Attempting to modify the list will throw an UnsupportedOperationException
// unmodifiableList.add("date"); // Uncommenting this line will cause an exception
}
}
Output:
Unmodifiable List: [apple, banana, cherry]
Using collectingAndThen() for Custom Transformations
This example shows how to use collectingAndThen() to collect the elements into a list and then transform the list into a string.
Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CustomTransformationExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Collect the elements into a list and then transform the list into a string
String result = numbers.stream()
.collect(Collectors.collectingAndThen(
Collectors.toList(),
list -> list.stream()
.map(String::valueOf)
.collect(Collectors.joining(", "))
));
System.out.println("Result: " + result);
}
}
Output:
Result: 1, 2, 3, 4, 5
Real-World Use Case
Finding the Longest String and Converting to Upper Case
In real-world applications, the collectingAndThen() method can be used to find the longest string in a list and then convert it to upper case.
Example
import java.util.Arrays;
import java.util.List;
import java.util.Comparator;
import java.util.stream.Collectors;
public class LongestStringExample {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
// Find the longest string and convert it to upper case
String longestUpperCase = words.stream()
.collect(Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparingInt(String::length)),
longest -> longest.get().toUpperCase()
));
System.out.println("Longest String in Upper Case: " + longestUpperCase);
}
}
Output:
Longest String in Upper Case: BANANA
Conclusion
The Collectors.collectingAndThen() method is used to perform a collection operation and then apply a finishing transformation to the result. This method is particularly useful for post-processing the result of a collection operation into another form. By understanding and using this method, you can efficiently manage complex collection operations in your Java applications.
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