Java中如何使用lambda表达式分类groupby

Java中如何使用lambda表达式分类groupby

Java中如何使用lambda表达式分类groupby

分类问题场景

比如一群学生根据性别和年龄排队,Student类有性别gender、年龄age属性,将同性别,同年龄的学生归为一类

gender age name 队伍
man 12 Li Hua 队伍1
man 12 Zhang San 队伍1
man 13 Li Si 队伍2
woman 12 Xiao Hua 队伍3
woman 12 Xiao Fang 队伍3

传统手写方式

使用for循环遍历

java 复制代码
public static void main(String[] args) {
    // 读取学生信息
    List<Student> students = generateStudents();
    // 排队
    Map<String, Map<Integer, List<Student>>> queue = queueUp(students);
    // 打印队伍结果
    printQueue(queue);
}

private static Map<String, Map<Integer, List<Student>>> queueUp(List<Student> students) {
    // 队伍结果
    Map<String, Map<Integer, List<Student>>> queue = new HashMap<>();
    // 传统排队方式
    for (Student student : students) {
        if (!queue.containsKey(student.getGender())) {
            queue.put(student.getGender(), new HashMap<>());
        }
        Map<Integer, List<Student>> ageMap = queue.get(student.getGender());
        if (!ageMap.containsKey(student.getAge())) {
            List<Student> list = new ArrayList<>();
            list.add(student);
            ageMap.put(student.getAge(), list);
        } else {
            ageMap.get(student.getAge()).add(student);
        }
    }

    return queue;
}

输出结果

shell 复制代码
|gender|age|name      |
|------|---|----------|
|woman |12 |Xiao Hua  |
|woman |12 |Xiao Fang |
|man   |12 |Li Hua    |
|man   |12 |Zhang San |
|man   |13 |Li Si     |

lambda使用groupBy()方法一行结束!!!

java 复制代码
private static Map<String, Map<Integer, List<Student>>> queueUpWithLambda(List<Student> students) {
    return students.stream().collect(Collectors.groupingBy(Student::getGender, Collectors.groupingBy(Student::getAge)));
}

完整代码

java 复制代码
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class DemoForGroupBy {

    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    public static class Student {
        private String gender;

        private int age;

        private String name;

    }

    public static void main(String[] args) {
        // 读取学生信息
        List<Student> students = generateStudents();

        // 排队
        Map<String, Map<Integer, List<Student>>> queue = queueUp(students);

        // 打印队伍结果
        printQueue(queue);

        queue = queueUpWithLambda(students);

        printQueue(queue);

    }

    private static Map<String, Map<Integer, List<Student>>> queueUp(List<Student> students) {
        // 队伍结果
        Map<String, Map<Integer, List<Student>>> queue = new HashMap<>();
        // 传统排队方式
        for (Student student : students) {
            if (!queue.containsKey(student.getGender())) {
                queue.put(student.getGender(), new HashMap<>());
            }
            Map<Integer, List<Student>> ageMap = queue.get(student.getGender());
            if (!ageMap.containsKey(student.getAge())) {
                List<Student> list = new ArrayList<>();
                list.add(student);
                ageMap.put(student.getAge(), list);
            } else {
                ageMap.get(student.getAge()).add(student);
            }
        }

        return queue;
    }

    private static Map<String, Map<Integer, List<Student>>> queueUpWithLambda(List<Student> students) {
        return students.stream().collect(Collectors.groupingBy(Student::getGender, Collectors.groupingBy(Student::getAge)));
    }

    private static List<Student> generateStudents() {
        List<Student> students = new ArrayList<>();
        String[] genderArray = new String[]{"man", "man", "man", "woman", "woman"};
        int[] ageArray = new int[]{12, 12, 13, 12, 12};
        String[] nameArray = new String[]{"Li Hua", "Zhang San", "Li Si", "Xiao Hua", "Xiao Fang"};
        for (int i = 0; i < nameArray.length; i++) {
            Student student = new Student(genderArray[i], ageArray[i], nameArray[i]);
            students.add(student);
        }
        return students;
    }

    private static void printQueue(Map<String, Map<Integer, List<Student>>> queue) {
        System.out.printf("|%-6s|%-3s|%-10s|%n", "gender", "age", "name");
        System.out.printf("|%-6s|%-3s|%-10s|%n", "------", "---", "----------");
        for (Map.Entry<String, Map<Integer, List<Student>>> entry : queue.entrySet()) {
            for (Map.Entry<Integer, List<Student>> e : entry.getValue().entrySet()) {
                for (Student student : e.getValue()) {
                    System.out.printf("|%-6s|%-3d|%-10s|%n", student.getGender(), student.getAge(), student.getName());
                }
            }
        }
    }

}
相关推荐
Boop_wu1 分钟前
[Java EE] 多线程编程进阶
java·数据库·java-ee
w***375119 分钟前
SpringBoot【实用篇】- 测试
java·spring boot·后端
谁刺我心21 分钟前
C++三种智能指针unique、shared、weak
开发语言·c++
深瞳智检24 分钟前
学习应用 第001期-Windows 10 用 CMD 安装 MySQL 全流程解析(免安装版)
数据库·windows·mysql·压缩包·环境安装
q***448135 分钟前
从零开始在Windows系统上搭建一个node.js后端服务项目
windows·node.js
q***614142 分钟前
Java实战:Spring Boot实现WebSocket实时通信
java·spring boot·websocket
k***825142 分钟前
Ubuntu介绍、与centos的区别、基于VMware安装Ubuntu Server 22.04、配置远程连接、安装jdk+Tomcat
java·ubuntu·centos
AGANCUDA1 小时前
qt使用osg显示pcd点云的例子
开发语言·qt
2301_815686451 小时前
extern
java·开发语言
q***56381 小时前
Java进阶-SPI机制
java·开发语言