Home > Java > javaTutorial > body text

Stream API in Java 8: How to use Collectors class for grouping and statistics of collections

王林
Release: 2023-07-31 18:21:15
Original
1139 people have browsed it

Stream API in Java 8: How to use the Collectors class for grouping and statistics of collections

Introduction:
In Java 8, the Stream API is introduced, which is a concept of functional programming , allows us to process collection data in a more concise and elegant way. The Stream API provides rich functionality, one of which is grouping and counting collections. This article will introduce how to use the Collectors class to achieve this functionality.

  1. Group of collections
    In actual development, we often need to group collections according to a certain attribute to facilitate subsequent processing. In Java 8, you can use the groupBy() method of the Collectors class to implement grouping of collections.

The sample code is as follows:

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

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

    public String getName() {
        return name;
    }

    public String getGender() {
        return gender;
    }

    public int getAge() {
        return age;
    }
}

List<Person> persons = Arrays.asList(
        new Person("John", "male", 20),
        new Person("Jane", "female", 25),
        new Person("Tom", "male", 30),
        new Person("Emily", "female", 35)
);

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

System.out.println(groupedByGender);
Copy after login

The output result is:

{female=[Person{name='Jane', gender='female', age=25}, Person{name='Emily', gender='female', age=35}], male=[Person{name='John', gender='male', age=20}, Person{name='Tom', gender='male', age=30}]}
Copy after login

In the above code, we first created a Person class as an example, which contains name, gender and age attributes. Then a List collection of Person objects is created. Next, convert the collection into a stream via the stream() method. Finally, use the groupBy() method of the Collectors class to group according to the gender attribute of the Person object, and the results are saved in a Map collection.

  1. Statistics of collections
    In practice, we may need to count the elements in the collection, such as calculating the number of elements, summing, averaging, etc. The Stream API of Java 8 provides a series of statistical methods, which we can use the summingInt(), averagingInt(), counting() and other methods of the Collectors class to implement.

The sample code is as follows:

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

int sum = numbers.stream().collect(Collectors.summingInt(Integer::intValue));
double average = numbers.stream().collect(Collectors.averagingInt(Integer::intValue));
long count = numbers.stream().collect(Collectors.counting());

System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Count: " + count);
Copy after login

The output result is:

Sum: 15
Average: 3.0
Count: 5
Copy after login

In the above code, we first create a List of Integer type, which contains a series of number. Next, the summingInt() method is used to calculate the sum, the averagingInt() method is used to calculate the average, and the counting() method is used to calculate the number. Finally, the results are obtained through the collect() method of the Collectors class.

Summary:
Through the Stream API and Collectors class in Java 8, we can group and perform statistical operations on collections in a more concise and elegant way. This feature not only improves the readability of the code, but also greatly enhances the flexibility of the program.

The above is this article’s introduction to collection grouping and statistics of the Stream API and Collectors class in Java 8. I hope it will be helpful to you. Thanks!

The above is the detailed content of Stream API in Java 8: How to use Collectors class for grouping and statistics of collections. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template