🎓 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
In Java, Collectors is a utility class in the java.util.stream package that provides various methods for collecting stream elements into different types of results, such as lists, sets, or maps. It is commonly used in conjunction with the Stream API to process and collect data efficiently.
Table of Contents
- What are
Collectors? - Commonly Used Methods
- Examples of
Collectors - Real-World Use Case
- Conclusion
1. What are Collectors?
Collectors is a final class that provides static methods for obtaining Collector instances. These instances implement various reduction operations, such as accumulating elements into collections, summarizing elements, and joining strings.
2. Commonly Used Methods
Here are some commonly used methods in the Collectors class:
toList(): Collects elements into aList.toSet(): Collects elements into aSet.toMap(): Collects elements into aMap.joining(): Concatenates elements into aString.counting(): Counts the number of elements.summarizingInt(),summarizingDouble(),summarizingLong(): Collects statistics, such as count, sum, min, average, and max.groupingBy(): Groups elements by a classifier function.partitioningBy(): Partitions elements into two groups based on a predicate.
3. Examples of Collectors
Example 1: Collecting to a List
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectToListExample {
public static void main(String[] args) {
List<String> list = Stream.of("apple", "banana", "cherry")
.collect(Collectors.toList());
System.out.println("List: " + list);
}
}
Output:
List: [apple, banana, cherry]
Example 2: Collecting to a Set
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectToSetExample {
public static void main(String[] args) {
Set<String> set = Stream.of("apple", "banana", "apple")
.collect(Collectors.toSet());
System.out.println("Set: " + set);
}
}
Output:
Set: [banana, apple]
Example 3: Collecting to a Map
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectToMapExample {
public static void main(String[] args) {
Map<String, Integer> map = Stream.of("apple", "banana", "cherry")
.collect(Collectors.toMap(fruit -> fruit, String::length));
System.out.println("Map: " + map);
}
}
Output:
Map: {banana=6, cherry=6, apple=5}
Example 4: Joining Strings
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JoiningExample {
public static void main(String[] args) {
String result = Stream.of("apple", "banana", "cherry")
.collect(Collectors.joining(", "));
System.out.println("Joined String: " + result);
}
}
Output:
Joined String: apple, banana, cherry
Example 5: Counting Elements
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CountingExample {
public static void main(String[] args) {
long count = Stream.of("apple", "banana", "cherry")
.collect(Collectors.counting());
System.out.println("Count: " + count);
}
}
Output:
Count: 3
Example 6: Grouping By
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GroupingByExample {
public static void main(String[] args) {
Map<Integer, List<String>> groupedByLength = Stream.of("apple", "banana", "cherry")
.collect(Collectors.groupingBy(String::length));
System.out.println("Grouped by Length: " + groupedByLength);
}
}
Output:
Grouped by Length: {5=[apple], 6=[banana, cherry]}
Example 7: Partitioning By
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class PartitioningByExample {
public static void main(String[] args) {
Map<Boolean, List<String>> partitioned = Stream.of("apple", "banana", "cherry")
.collect(Collectors.partitioningBy(s -> s.length() > 5));
System.out.println("Partitioned: " + partitioned);
}
}
Output:
Partitioned: {false=[apple], true=[banana, cherry]}
4. Real-World Use Case: Summarizing Integer Statistics
import java.util.IntSummaryStatistics;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class SummarizingIntExample {
public static void main(String[] args) {
IntSummaryStatistics stats = IntStream.of(1, 2, 3, 4, 5)
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Summary Statistics: " + stats);
}
}
Output:
Summary Statistics: IntSummaryStatistics{count=5, sum=15, min=1, average=3.000000, max=5}
Conclusion
The Collectors class is used in Java for collecting and processing data using the Stream API. Its various methods allow developers to accumulate elements into collections, summarize data, and perform other reduction operations efficiently. Using Collectors can greatly enhance code readability and maintainability, especially in data processing contexts.
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