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

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

王林
王林Original
2023-07-31 18:21:151103browse

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);

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}]}

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);

The output result is:

Sum: 15
Average: 3.0
Count: 5

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!

Statement:
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