🎓 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 collect() method in Java, part of the java.util.stream.IntStream interface, is used to perform a mutable reduction operation on the elements of the stream. This method is highly versatile and can be used to accumulate elements into a Collection, StringBuilder, or any other type of mutable container.
Table of Contents
- Introduction
collect()Method Syntax- Understanding
collect() - Examples
- Basic Usage
- Using
collect()with Custom Collector
- Real-World Use Case
- Conclusion
Introduction
The collect() method performs a mutable reduction operation on the elements of the stream using a Collector. This method is a terminal operation, meaning it consumes the stream and produces a result.
collect() Method Syntax
There are two main overloads of the collect() method in IntStream:
- Using a
Collector:
<R> R collect(Collector<? super Integer, A, R> collector)
- Using supplier, accumulator, and combiner:
<R> R collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner)
Parameters:
collector: TheCollectordescribing the reduction.supplier: A function that provides a new mutable result container.accumulator: An associative, non-interfering, stateless function for incorporating an additional element into a result container.combiner: An associative, non-interfering, stateless function for combining two result containers.
Returns:
- The result of the reduction.
Throws:
- This method does not throw any exceptions.
Understanding collect()
The collect() method is used to gather the elements of a stream into a container, such as a List, Set, or Map. It is highly flexible, allowing you to define custom reduction operations using a combination of supplier, accumulator, and combiner functions.
Examples
Basic Usage
To demonstrate the basic usage of collect(), we will create an IntStream and use collect() to accumulate its elements into a List<Integer>.
Example
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class CollectExample {
public static void main(String[] args) {
IntStream intStream = IntStream.of(1, 2, 3, 4, 5);
// Collect the elements into a List<Integer>
List<Integer> list = intStream.boxed().collect(Collectors.toList());
// Print the list
System.out.println(list);
}
}
Output:
[1, 2, 3, 4, 5]
Using collect() with Custom Collector
This example shows how to use collect() with a custom collector to accumulate elements into a StringBuilder.
Example
import java.util.stream.IntStream;
public class CustomCollectorExample {
public static void main(String[] args) {
IntStream intStream = IntStream.of(1, 2, 3, 4, 5);
// Collect the elements into a StringBuilder
StringBuilder stringBuilder = intStream.collect(
StringBuilder::new, // Supplier
(sb, i) -> sb.append(i).append(", "), // Accumulator
StringBuilder::append // Combiner
);
// Print the StringBuilder
System.out.println(stringBuilder);
}
}
Output:
1, 2, 3, 4, 5,
Real-World Use Case
Collecting Scores into a Map
In real-world applications, the collect() method can be used to collect scores into a Map with the student's name as the key and the score as the value.
Example
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class ScoresToMapExample {
public static void main(String[] args) {
String[] students = {"Alice", "Bob", "Charlie", "David", "Eve"};
int[] scores = {85, 92, 78, 88, 90};
// Create a map of student names to scores
Map<String, Integer> studentScores = IntStream.range(0, students.length)
.boxed()
.collect(Collectors.toMap(i -> students[i], i -> scores[i]));
// Print the map
System.out.println(studentScores);
}
}
Output:
{Bob=92, Eve=90, Alice=85, Charlie=78, David=88}
Conclusion
The IntStream.collect() method is used to perform a mutable reduction operation on the elements of the stream. This method is particularly useful for gathering elements into a collection or any other mutable container. By understanding and using this method, you can efficiently manage and process streams of integer values 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