Home Java javaTutorial 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

Jul 31, 2023 pm 06:21 PM
stream collectors Group statistics

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:

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

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:

1

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

1

2

3

4

5

6

7

8

9

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:

1

2

3

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1259
29
C# Tutorial
1233
24
Implementation of linear and pie chart functions in Vue statistical charts Implementation of linear and pie chart functions in Vue statistical charts Aug 19, 2023 pm 06:13 PM

The linear and pie chart functions of Vue statistical charts are implemented in the field of data analysis and visualization. Statistical charts are a very commonly used tool. As a popular JavaScript framework, Vue provides convenient methods to implement various functions, including the display and interaction of statistical charts. This article will introduce how to use Vue to implement linear and pie chart functions, and provide corresponding code examples. Linear graph function implementation A linear graph is a type of chart used to display trends and changes in data. In Vue, we can use some excellent

How to implement data statistics and analysis in uniapp How to implement data statistics and analysis in uniapp Oct 24, 2023 pm 12:37 PM

How to implement data statistics and analysis in uniapp 1. Background introduction Data statistics and analysis are a very important part of the mobile application development process. Through statistics and analysis of user behavior, developers can have an in-depth understanding of user preferences and usage habits. Thereby optimizing product design and user experience. This article will introduce how to implement data statistics and analysis functions in uniapp, and provide some specific code examples. 2. Choose appropriate data statistics and analysis tools. The first step to implement data statistics and analysis in uniapp is to choose the appropriate data statistics and analysis tools.

Use Google Analytics to count website data in Beego Use Google Analytics to count website data in Beego Jun 22, 2023 am 09:19 AM

With the rapid development of the Internet, the use of Web applications is becoming more and more common. How to monitor and analyze the usage of Web applications has become a focus of developers and website operators. Google Analytics is a powerful website analytics tool that can track and analyze the behavior of website visitors. This article will introduce how to use Google Analytics in Beego to collect website data. 1. To register a Google Analytics account, you first need to

How to quickly build a statistical chart system under the Vue framework How to quickly build a statistical chart system under the Vue framework Aug 21, 2023 pm 05:48 PM

How to quickly build a statistical chart system under the Vue framework. In modern web applications, statistical charts are an essential component. As a popular front-end framework, Vue.js provides many convenient tools and components that can help us quickly build a statistical chart system. This article will introduce how to use the Vue framework and some plug-ins to build a simple statistical chart system. First, we need to prepare a Vue.js development environment, including installing Vue scaffolding and some related plug-ins. Execute the following command in the command line

Steps of statistical analysis Steps of statistical analysis Jun 28, 2023 pm 03:27 PM

Statistical analysis often refers to the process of sorting, classifying and interpreting collected relevant data. The basic steps of statistical analysis include: 1. Collect data; 2. Organize data; 3. Analyze data.

How to use MySQL's COUNT function to count the number of rows in a data table How to use MySQL's COUNT function to count the number of rows in a data table Jul 25, 2023 pm 02:09 PM

How to use MySQL's COUNT function to count the number of rows in a data table. In MySQL, the COUNT function is a very powerful function that is used to count the number of rows in a data table that meet specific conditions. This article will introduce how to use MySQL's COUNT function to count the number of rows in a data table, and provide relevant code examples. The syntax of the COUNT function is as follows: SELECTCOUNT(column_name)FROMtable_nameWHEREconditi

How to debug Java Stream operations in IntelliJ IDEA How to debug Java Stream operations in IntelliJ IDEA May 09, 2023 am 11:25 AM

Stream operation is a highlight of Java8! Although java.util.stream is very powerful, there are still many developers who rarely use it in actual work. One of the most complained reasons is that it is difficult to debug. This was indeed the case at the beginning, because streaming operations such as stream cannot be used in DEBUG When it is one line of code, when it comes to the next step, many operations are actually passed at once, so it is difficult for us to judge which line in it is the problem. Plug-in: JavaStreamDebugger If the IDEA version you are using is relatively new, this plug-in is already included and does not need to be installed. If it is not installed yet, install it manually and then continue below.

How to use SQL statements for data aggregation and statistics in MySQL? How to use SQL statements for data aggregation and statistics in MySQL? Dec 17, 2023 am 08:41 AM

How to use SQL statements for data aggregation and statistics in MySQL? Data aggregation and statistics are very important steps when performing data analysis and statistics. As a powerful relational database management system, MySQL provides a wealth of aggregation and statistical functions, which can easily perform data aggregation and statistical operations. This article will introduce the method of using SQL statements to perform data aggregation and statistics in MySQL, and provide specific code examples. 1. Use the COUNT function for counting. The COUNT function is the most commonly used

See all articles