search
HomeJavajavaTutorialHow to use Java Collectors tool class
How to use Java Collectors tool classMay 15, 2023 pm 09:07 PM
javacollectors

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

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

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

    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("-", "{", "}")));
    }

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

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

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

    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
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    带你搞懂Java结构化数据处理开源库SPL带你搞懂Java结构化数据处理开源库SPLMay 24, 2022 pm 01:34 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于结构化数据处理开源库SPL的相关问题,下面就一起来看一下java下理想的结构化数据处理类库,希望对大家有帮助。

    Java集合框架之PriorityQueue优先级队列Java集合框架之PriorityQueue优先级队列Jun 09, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于PriorityQueue优先级队列的相关知识,Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的,下面一起来看一下,希望对大家有帮助。

    完全掌握Java锁(图文解析)完全掌握Java锁(图文解析)Jun 14, 2022 am 11:47 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于java锁的相关问题,包括了独占锁、悲观锁、乐观锁、共享锁等等内容,下面一起来看一下,希望对大家有帮助。

    一起聊聊Java多线程之线程安全问题一起聊聊Java多线程之线程安全问题Apr 21, 2022 pm 06:17 PM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于多线程的相关问题,包括了线程安装、线程加锁与线程不安全的原因、线程安全的标准类等等内容,希望对大家有帮助。

    Java基础归纳之枚举Java基础归纳之枚举May 26, 2022 am 11:50 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于枚举的相关问题,包括了枚举的基本操作、集合类对枚举的支持等等内容,下面一起来看一下,希望对大家有帮助。

    详细解析Java的this和super关键字详细解析Java的this和super关键字Apr 30, 2022 am 09:00 AM

    本篇文章给大家带来了关于Java的相关知识,其中主要介绍了关于关键字中this和super的相关问题,以及他们的一些区别,下面一起来看一下,希望对大家有帮助。

    Java数据结构之AVL树详解Java数据结构之AVL树详解Jun 01, 2022 am 11:39 AM

    本篇文章给大家带来了关于java的相关知识,其中主要介绍了关于平衡二叉树(AVL树)的相关知识,AVL树本质上是带了平衡功能的二叉查找树,下面一起来看一下,希望对大家有帮助。

    java中封装是什么java中封装是什么May 16, 2019 pm 06:08 PM

    封装是一种信息隐藏技术,是指一种将抽象性函式接口的实现细节部分包装、隐藏起来的方法;封装可以被认为是一个保护屏障,防止指定类的代码和数据被外部类定义的代码随机访问。封装可以通过关键字private,protected和public实现。

    See all articles

    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 agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

    PhpStorm Mac version

    PhpStorm Mac version

    The latest (2018.2.1) professional PHP integrated development tool

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),