Home Java 8 - Stream Collectors
Post
Cancel

Java 8 - Stream Collectors

Java 8 - Stream Collectors

treams are a sequence of elements that can be processed in parallel or sequentially. One of the most useful features of Streams is the ability to collect the result of a Stream into a collection or a single value. In this blog, we will explore the various ways to collect the result in Stream Java 8 with code example

Collectors

Java 8 introduced the Collectors class, which provides a set of predefined collectors that can be used to collect the result of a Stream into various collections. The Collectors class provides methods to collect the result into a List, Set, Map, or even into a custom collection. Let’s explore some of the commonly used collectors.

  • toList()

The toList() collector is used to collect the result of a Stream into a List.

Example:

1
2
3
List<String> names = Stream.of("John", "Mary", "Peter")
                            .collect(Collectors.toList());

  • toSet()

The toSet() collector is used to collect the result of a Stream into a Set.

1
2
3
Set<String> names = Stream.of("John", "Mary", "Peter")
  .collect(Collectors.toSet());

  • toMap()

The toMap() collector is used to collect the result of a Stream into a Map.

1
2
3
4
5
Map<String, Integer> ageMap = Stream.of(new Person("John", 25),
                                        new Person("Mary", 30),
                                        new Person("Peter", 35))
                                    .collect(Collectors.toMap(Person::getName, Person::getAge));

In the above example, we have a Stream of Person objects. We have used the toMap() collector to collect the result into a Map, where the name of the person is the key, and the age of the person is the value.

  • joining()

The joining() collector is used to concatenate the elements of a Stream into a single string.

Example:

1
2
3
String names = Stream.of("John", "Mary", "Peter")
                        .collect(Collectors.joining(", "));

In the above example, we have used the joining() collector to concatenate the names of the people into a single string separated by a comma.

  • summingInt()

The summingInt() collector is used to sum the elements of a Stream.

Example:

1
2
3
4
int sum = IntStream.of(1, 2, 3, 4, 5)
                    .boxed()
                    .collect(Collectors.summingInt(Integer::intValue));

  • groupingBy

The groupingBy collector is used to groupingBy the elements of a Stream.

Suppose we have a Person class with properties such as id, name, age, and gender. We want to group the list of Person objects based on their gender.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.*;
import java.util.stream.Collectors;

public class Person {
    private int id;
    private String name;
    private int age;
    private String gender;

    public Person(int id, String name, int age, String gender) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    // getter setter

    public static void main(String[] args) {
        List<Person> persons = List.of(
                new Person(1, "John", 20, "Male"),
                new Person(2, "Sara", 25, "Female"),
                new Person(3, "David", 30, "Male"),
                new Person(4, "Alice", 35, "Female"),
                new Person(5, "Michael", 40, "Male"),
                new Person(6, "Emily", 45, "Female")
        );

        Map<String, List<Person>> genderToPersons = persons.stream()
                .collect(Collectors.groupingBy(Person::getGender));

        genderToPersons.forEach((gender, personsList) -> {
            System.out.println("Gender: " + gender);
            System.out.println(personsList);
        });
    }
}

In this example, we first create a list of Person objects. Then, we use the Collectors.groupingBy method to group the Person objects based on their gender property. The groupingBy method returns a Map<String, List>, where the keys are the values of the gender property, and the values are lists of Person objects with the corresponding gender.

Finally, we iterate through the map and print out the gender and the list of Person objects for that gender.

Output:

1
2
3
4
Gender: Male
[Person{id=1, name='John', age=20, gender='Male'}, Person{id=3, name='David', age=30, gender='Male'}, Person{id=5, name='Michael', age=40, gender='Male'}]
Gender: Female
[Person{id=2, name='Sara', age=25, gender='Female'}, Person{id=4, name='Alice', age=35, gender='Female'}, Person{id=6, name='Emily', age=45, gender='Female'}]

Conclusion

In conclusion, Java 8 streams provide a powerful and efficient way to process collections of data. The collect() method is a key part of this functionality, allowing for the accumulation of results into a container or object.

This post is licensed under CC BY 4.0 by the author.