Introduction
The Collectors
class in Java 8 is part of the java.util.stream
package and provides various utility methods to collect the results of stream operations. It's primarily used with the Stream.collect()
method to convert a stream into a different form, such as a List
, Set
, Map
, or even a concatenated String
. Collectors
simplify tasks like grouping, partitioning, and reducing data from streams.
In this tutorial, we will explore several commonly used Collectors
methods with examples.
Table of Contents
- Example 1: Collect to a List
- Example 2: Collect to a Set
- Example 3: Collect to a Map
- Example 4: Joining Elements into a String
- Example 5: Summing Elements
- Example 6: Averaging Values
- Example 7: Grouping Elements by a Key
- Example 8: Partitioning Elements by a Predicate
- Example 9: Counting Elements
- Example 10: Collecting and Reducing Elements
Example 1: Collect to a List
The most common use of the Collectors
class is to collect elements from a stream into a List
.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectToListExample {
public static void main(String[] args) {
List<String> cities = Arrays.asList("Mumbai", "Delhi", "Bangalore", "Chennai");
// Collecting the stream into a List
List<String> cityList = cities.stream().collect(Collectors.toList());
System.out.println(cityList);
}
}
Output
[Mumbai, Delhi, Bangalore, Chennai]
Explanation
- We use
Collectors.toList()
to collect the stream elements into aList
.
Example 2: Collect to a Set
You can use Collectors.toSet()
to collect elements from a stream into a Set
, which removes duplicates.
Code Example
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class CollectToSetExample {
public static void main(String[] args) {
List<String> cities = Arrays.asList("Mumbai", "Delhi", "Mumbai", "Bangalore");
// Collecting the stream into a Set
Set<String> citySet = cities.stream().collect(Collectors.toSet());
System.out.println(citySet);
}
}
Output
[Mumbai, Delhi, Bangalore]
Explanation
- The
Collectors.toSet()
method collects the stream elements into aSet
, removing duplicate entries.
Example 3: Collect to a Map
You can collect elements from a stream into a Map
using Collectors.toMap()
. In this example, we will map city names to their lengths.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class CollectToMapExample {
public static void main(String[] args) {
List<String> cities = Arrays.asList("Mumbai", "Delhi", "Bangalore");
// Collecting the stream into a Map (city name -> city name length)
Map<String, Integer> cityMap = cities.stream()
.collect(Collectors.toMap(city -> city, city -> city.length()));
System.out.println(cityMap);
}
}
Output
{Mumbai=6, Delhi=5, Bangalore=9}
Explanation
- The
Collectors.toMap()
method creates aMap
where the city names are the keys and their lengths are the values.
Example 4: Joining Elements into a String
You can use Collectors.joining()
to concatenate the elements of a stream into a single String
.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectJoiningExample {
public static void main(String[] args) {
List<String> cities = Arrays.asList("Mumbai", "Delhi", "Bangalore", "Chennai");
// Joining elements into a single String
String joinedCities = cities.stream().collect(Collectors.joining(", "));
System.out.println(joinedCities);
}
}
Output
Mumbai, Delhi, Bangalore, Chennai
Explanation
- The
Collectors.joining()
method concatenates the city names, separated by a comma and a space.
Example 5: Summing Elements
You can sum the numeric elements of a stream using Collectors.summingInt()
, summingLong()
, or summingDouble()
.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectSummingIntExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Summing all integers in the list
int sum = numbers.stream().collect(Collectors.summingInt(Integer::intValue));
System.out.println("Sum: " + sum);
}
}
Output
Sum: 15
Explanation
- The
Collectors.summingInt()
method is used to sum the integer values in the stream.
Example 6: Averaging Values
To calculate the average of elements, you can use Collectors.averagingInt()
, averagingLong()
, or averagingDouble()
.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectAveragingIntExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Calculating the average of all integers in the list
double average = numbers.stream().collect(Collectors.averagingInt(Integer::intValue));
System.out.println("Average: " + average);
}
}
Output
Average: 3.0
Explanation
- The
Collectors.averagingInt()
method calculates the average of the elements in the stream.
Example 7: Grouping Elements by a Key
You can use Collectors.groupingBy()
to group elements of a stream by a specific key.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class CollectGroupingByExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Amit", "Deepa", "Rahul", "Akhil");
// Grouping names by the first letter
Map<Character, List<String>> groupedByLetter = names.stream()
.collect(Collectors.groupingBy(name -> name.charAt(0)));
System.out.println(groupedByLetter);
}
}
Output
{A=[Amit, Akhil], D=[Deepa], R=[Rahul]}
Explanation
- The
Collectors.groupingBy()
method groups the names by the first letter of each name.
Example 8: Partitioning Elements by a Predicate
You can partition elements into two groups based on a predicate using Collectors.partitioningBy()
.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class CollectPartitioningByExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
// Partitioning numbers into even and odd
Map<Boolean, List<Integer>> partitioned = numbers.stream()
.collect(Collectors.partitioningBy(num -> num % 2 == 0));
System.out.println(partitioned);
}
}
Output
{false=[1, 3, 5], true=[2, 4, 6]}
Explanation
- The
Collectors.partitioningBy()
method splits the numbers into two groups: even and odd.
Example 9: Counting Elements
To count the number of elements in a stream, use Collectors.counting()
.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectCountingExample {
public static void main(String[] args) {
List<String> cities = Arrays.asList("Mumbai", "Delhi", "Bangalore", "Chennai");
// Counting the number of cities
long count = cities.stream().collect(Collectors.counting());
System.out.println("Number of cities: " + count);
}
}
Output
Number of cities: 4
Explanation
- The
Collectors.counting()
method returns the number of elements in the stream.
Example 10: Collecting and Reducing Elements
You can use Collectors.reducing()
to reduce elements in a stream using a custom binary operator.
Code Example
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectReducingExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Reducing the numbers to their sum
int sum = numbers.stream().collect(Collectors.reducing(0, (a, b) -> a + b));
System
.out.println("Sum using reducing: " + sum);
}
}
Output
Sum using reducing: 15
Explanation
- The
Collectors.reducing()
method reduces the stream's elements using a custom binary operator (sum in this case).
Conclusion
The Collectors
class in Java 8 provides powerful methods for working with streams. With Collectors
, you can transform, group, partition, and perform various operations on stream elements, making it easier to process data in a functional and concise way. These examples cover a range of common use cases, such as collecting to lists, maps, grouping, and more.
Comments
Post a Comment
Leave Comment