Table of Contents
Method
Practice instructions
1. Prerequisite Condition
2. Operation
Home Java javaTutorial How to use Java Collectors tool class

How to use Java Collectors tool class

May 15, 2023 pm 09:07 PM
java collectors

    Method

    ● maxBy: Get the largest element in the stream; minBy: Get the smallest element in the stream

    ● joining: merge, merge The elements in the stream are concatenated in the form of strings

    ● summingInt: map the elements in the stream into int type elements, and sum them

    ● averagingInt: map the elements in the stream into elements of type int, find the average value

    ● summarizingInt: Map the elements in the stream into elements of type int, and obtain the description information

    Practice instructions

    1. Prerequisite Condition

    Person class

    package com.example;
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import org.springframework.context.annotation.Configuration;
    import java.util.Objects;
    /**
     * @BelongsProject: StreamOperate
     * @BelongsPackage: com.example
     * @CreateTime: 2023-05-01  11:18
     * @Description: Person实体类
     * @Version: 1.0
     */
    public class Person implements Comparable<Person>{
        public String getName() {
            return name;
        }
        public Person setName(String name) {
            this.name = name;
            return this;
        }
        public int getAge() {
            return age;
        }
        public Person setAge(int age) {
            this.age = age;
            return this;
        }
        public int getScore() {
            return score;
        }
        public Person setScore(int score) {
            this.score = score;
            return this;
        }
        private String name;
        private int age;
        private int score;
        public Person(String name, int age, int score) {
            this.name = name;
            this.age = age;
            this.score = score;
        }
        public Person() {
        }
        @Override
        public String toString() {
            return "Person{" +
                    "name=&#39;" + name + &#39;\&#39;&#39; +
                    ", age=" + age +
                    ", score=" + score +
                    &#39;}&#39;;
        }
        @Override
        public boolean equals(Object o) {
            //地址相同,为true
            if (this == o) return true;
            //为null,并且类型不一样,为false
            if (o == null || getClass() != o.getClass()) return false;
            //向下转型,再去比较属性值
            Person person = (Person) o;
            //如果属性值相同,最后的结果为true
            return age == person.age && score == person.score && Objects.equals(name, person.name);
            //return false;
        }
        @Override
        public int hashCode() {
            return Objects.hash(name, age, score);
        }
        @Override
        public int compareTo(Person o) {
            return this.getScore()-o.getScore();
        }
    }
    Copy after login

    Data class

    package com.example;
    import org.springframework.context.annotation.Configuration;
    import java.util.ArrayList;
    /**
     * @BelongsProject: StreamOperate
     * @BelongsPackage: com.example
     * @CreateTime: 2023-05-01  11:08
     * @Description: Data类
     * @Version: 1.0
     */
    public class Data {
        public static ArrayList<Person> getData() {
            ArrayList<Person> personList = new ArrayList<>();
            personList.add(new Person("张三", 18, 90));
            personList.add(new Person("李四", 19, 100));
            personList.add(new Person("王五", 17, 60));
            personList.add(new Person("赵六", 18, 89));
            personList.add(new Person("孙七", 20, 96));
            personList.add(new Person("郑十", 20, 46));
            personList.add(new Person("周八", 20, 96));
            personList.add(new Person("周八", 20, 96));
            personList.add(new Person("吴九", 20, 45));
            personList.add(new Person("邓十一", 20, 35));
            personList.add(new Person("刘十二", 20, 99));
            personList.add(new Person("小十三", 20, 56));
            personList.add(new Person("小十三", 20, 56));
            return personList;
        }
    }
    Copy after login

    2. Operation

    maxBy: Get the largest element in the stream; minBy: Get the smallest element in the stream

    public static void main(String[] args) {
            Stream<Person> stream = Data.getData().stream();
            //maxBy:获取流中最大元素;minBy:获取流中最小元素
            System.out.println(Data.getData().stream().collect(Collectors.maxBy((ele1, ele2) -> ele1.getScore() - ele2.getScore())));
            System.out.println(Data.getData().stream().collect(Collectors.minBy((ele1, ele2) -> ele1.getAge() - ele2.getAge())));
    }
    Copy after login

    joining: Merge, join the elements in the stream in the form of a string

    public static void main(String[] args) {
            Stream<Person> stream = Data.getData().stream();
            //joining:合并,将流中的元素,以字符串的形式拼接起来
            //将集合中person对象的姓名拼接成一个字符串
            System.out.println(Data.getData().stream().map(Person::getName).collect(Collectors.joining()));
            System.out.println(Data.getData().stream().map(Person::getName).collect(Collectors.joining("-")));
            System.out.println(Data.getData().stream().map(Person::getName).collect(Collectors.joining("-", "{", "}")));
    }
    Copy after login

    summingInt: Map the elements in the stream into elements of type int, and sum them

    public static void main(String[] args) {
            Stream<Person> stream = Data.getData().stream();
    				//summingInt:把流中的元素映射成int类型的元素,求和
            System.out.println(Data.getData().stream().collect(Collectors.summingInt(Person::getScore)));
    }
    Copy after login

    averagingInt: Map the elements in the stream to elements of type int, and find the average value

    public static void main(String[] args) {
            Stream<Person> stream = Data.getData().stream();
            //averagingInt:把流中的元素映射成int类型的元素,求平均值
            System.out.println(Data.getData().stream().collect(Collectors.averagingInt(Person::getScore)));
    }
    Copy after login

    summarizingInt: Map the elements in the stream to elements of type int, and get the description information

    Requirement: Replace Person objects with scores greater than or equal to 80 in the stream with their names

     public static void main(String[] args) {
            Stream<Person> stream = Data.getData().stream();
            //summarizingInt:把流中的元素映射成int类型的元素,获取描述信息
            IntSummaryStatistics collect = Data.getData().stream().collect(Collectors.summarizingInt(Person::getScore));
            System.out.println(collect);
            System.out.println(collect.getCount());
            System.out.println(collect.getSum());
            System.out.println(collect.getMax());
            System.out.println(collect.getMax());
            System.out.println(collect.getAverage());
    Copy after login

    Output result:

    Java Collectors工具类怎么使用

    The above is the detailed content of How to use Java Collectors tool class. 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

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Hello Kitty Island Adventure: How To Get Giant Seeds
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌
    Two Point Museum: All Exhibits And Where To Find Them
    1 months ago By 尊渡假赌尊渡假赌尊渡假赌

    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)

    Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

    Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

    Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

    Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

    Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

    Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

    Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

    Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

    Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

    Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    See all articles