Java Collectors

Java Collectors is a utility class in the Java Stream API that provides methods to collect elements from a stream into various data structures. It is used in conjunction with the Java Stream API to perform a wide variety of data processing tasks.

Here are some common methods provided by the Collectors class:

  1. toList(): This method returns a Collector that accumulates the input elements into a new List.

Example:

List<String> names = Stream.of("Alice", "Bob", "Charlie")
                             .collect(Collectors.toList());
  1. toSet(): This method returns a Collector that accumulates the input elements into a new Set.

Example:

Set<Integer> numbers = Stream.of(1, 2, 3, 3, 4, 5, 5)
                              .collect(Collectors.toSet());
  1. toMap(): This method returns a Collector that accumulates elements into a Map. It takes two arguments, a function to extract the key and another function to extract the value.

Example:

Map<String, Integer> nameToAge = Stream.of("Alice", "Bob", "Charlie")
                                       .collect(Collectors.toMap(Function.identity(), String::length));
  1. joining(): This method returns a Collector that concatenates the input elements into a single String, separated by a delimiter.

Example:

String joinedNames = Stream.of("Alice", "Bob", "Charlie")
                           .collect(Collectors.joining(", "));
  1. counting(): This method returns a Collector that counts the number of elements in the stream.

Example:

long count = Stream.of("Alice", "Bob", "Charlie")
                   .collect(Collectors.counting());

There are many more methods provided by the Collectors class, each serving a specific purpose in collecting and processing data from streams.

Java Collectors Example: Fetching data as a List

Sure, here’s an example of using Java Collectors to fetch data from a stream and store it in a List:

Suppose we have a list of Person objects:

List<Person> people = Arrays.asList(
    new Person("Alice", 25),
    new Person("Bob", 30),
    new Person("Charlie", 35)
);

We can use the stream() method of the List interface to create a stream of Person objects and then use the collect() method along with the Collectors.toList() method to store the stream elements in a new List:

List<Person> peopleList = people.stream()
                                .collect(Collectors.toList());

This code creates a new stream of Person objects using the stream() method, and then uses the collect() method to collect the stream elements into a List using the Collectors.toList() method.

Note that in this example, the Person class must have a default no-argument constructor and appropriate getters and setters for its properties. This allows the Collectors.toList() method to correctly create a new List of Person objects.

Java Collectors Example: Converting Data as a Set

Certainly! Here’s an example of using Java Collectors to convert data from a stream into a Set:

Suppose we have a List of integers:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 4, 5, 5);

We can use the stream() method of the List interface to create a stream of Integer objects and then use the collect() method along with the Collectors.toSet() method to store the stream elements in a new Set:

Set<Integer> numberSet = numbers.stream()
                                .collect(Collectors.toSet());

This code creates a new stream of Integer objects using the stream() method, and then uses the collect() method to collect the stream elements into a Set using the Collectors.toSet() method.

Note that in this example, the numbers list may contain duplicate elements, but when it is converted to a Set using Collectors.toSet(), duplicates are automatically removed. The resulting Set will contain only the distinct elements of the original list.

Also note that the order of the elements in the resulting Set is not guaranteed to be the same as the order of the elements in the original List.

Java Collectors Example: using sum method

Sure, here’s an example of using the sum() method of the Collectors class in Java to calculate the sum of a list of integers:

Suppose we have a List of integers:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

We can use the stream() method of the List interface to create a stream of Integer objects and then use the collect() method along with the Collectors.summingInt() method to calculate the sum of the stream elements:

int sum = numbers.stream()
                 .collect(Collectors.summingInt(Integer::intValue));

This code creates a new stream of Integer objects using the stream() method, and then uses the collect() method to collect the stream elements and calculate the sum using the Collectors.summingInt() method.

The summingInt() method takes a function that extracts an integer value from each element of the stream. In this case, we use a method reference to the intValue() method of the Integer class to extract the integer value of each element.

After the stream elements have been transformed into integer values, the summingInt() method calculates their sum and returns the result as an int.

In this example, the value of the sum variable will be 15, which is the sum of the elements in the numbers list.

Java Collectors Example: Getting Product Average Price

Sure, here’s an example of using Java Collectors to calculate the average price of products in a list:

Suppose we have a List of Product objects:

class Product {
    private String name;
    private double price;

    public Product(String name, double price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }
}

List<Product> products = Arrays.asList(
    new Product("Apple", 1.0),
    new Product("Orange", 1.5),
    new Product("Banana", 0.5),
    new Product("Grapes", 2.0),
    new Product("Mango", 3.0)
);

We can use the stream() method of the List interface to create a stream of Product objects and then use the collect() method along with the Collectors.averagingDouble() method to calculate the average price of the products:

double averagePrice = products.stream()
                              .collect(Collectors.averagingDouble(Product::getPrice));

This code creates a new stream of Product objects using the stream() method, and then uses the collect() method to collect the stream elements and calculate the average price using the Collectors.averagingDouble() method.

The averagingDouble() method takes a function that extracts a double value from each element of the stream. In this case, we use a method reference to the getPrice() method of the Product class to extract the price of each product.

After the stream elements have been transformed into double values, the averagingDouble() method calculates their average and returns the result as a double.

In this example, the value of the averagePrice variable will be 1.4, which is the average price of the products in the products list.

Java Collectors Example: Counting Elements

Sure, here’s an example of using Java Collectors to count the number of elements in a list that satisfy a certain condition:

Suppose we have a List of integers:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

We can use the stream() method of the List interface to create a stream of Integer objects and then use the filter() method to filter the elements of the stream that satisfy a condition (in this case, we’ll count the number of even numbers in the list). Then, we can use the count() method of the Stream interface to count the number of elements in the filtered stream:

long count = numbers.stream()
                    .filter(n -> n % 2 == 0)
                    .count();

This code creates a new stream of Integer objects using the stream() method, and then uses the filter() method to filter the stream elements based on whether they are even numbers (i.e., their remainder when divided by 2 is 0).

After the stream has been filtered, the count() method of the Stream interface counts the number of remaining elements in the stream.

In this example, the value of the count variable will be 2, which is the number of even numbers in the numbers list.

Note that in this example, we didn’t use the collect() method of the Stream interface or any of the Collectors methods. However, the count() method is often used in conjunction with Collectors.counting() to count the number of elements in a stream. Here’s an example of how that could look:

long count = numbers.stream()
                    .filter(n -> n % 2 == 0)
                    .collect(Collectors.counting());

This code is equivalent to the previous example, but uses the Collectors.counting() method to count the number of elements in the filtered stream. The resulting value of count will be the same (2).