Java List 根据List中对象的属性值是否相同作为同一组,分割成多个连续的子List

需求:Java List 根据List中对象的属性值是否相同作为同一组,分割成多个连续的子List
java 复制代码
package com.suncd.trs.provider.controller;


import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class ListGrouping {

    /**
     * 将List按照对象属性值是否相同进行分组,分割成多个连续的子List
     * @param list 原始List
     * @param keyExtractor 提取对象属性值的函数
     * @param <T> List中对象的类型
     * @param <K> 属性值的类型
     * @return 分割后的子List集合
     */
    public static <T, K> List<List<T>> groupByProperty(List<T> list, Function<T, K> keyExtractor) {
        if (list == null || keyExtractor == null) {
            throw new IllegalArgumentException("List和keyExtractor不能为null");
        }

        List<List<T>> result = new ArrayList<>();
        if (list.isEmpty()) {
            return result;
        }

        List<T> currentGroup = new ArrayList<>();
        K previousKey = null;

        for (T item : list) {
            K currentKey = keyExtractor.apply(item);

            // 如果是第一个元素,或者当前属性值与前一个不同,则开始新组
            if (currentGroup.isEmpty() || !currentKey.equals(previousKey)) {
                if (!currentGroup.isEmpty()) {
                    result.add(currentGroup);
                }
                currentGroup = new ArrayList<>();
            }

            currentGroup.add(item);
            previousKey = currentKey;
        }

        // 添加最后一组
        if (!currentGroup.isEmpty()) {
            result.add(currentGroup);
        }

        return result;
    }

    // 示例使用
    public static void main(String[] args) {
        // 创建测试数据
        List<Person> people = new ArrayList<>();
        people.add(new Person("张三", 25));
        people.add(new Person("李四", 25));
        people.add(new Person("王五", 30));
        people.add(new Person("赵六", 27));
        people.add(new Person("钱七", 30));
        people.add(new Person("孙八", 25));
        people.add(new Person("周九", 35));

        // 按年龄分组
        List<List<Person>> groupedByAge = groupByProperty(people, Person::getAge);
        System.out.println("按年龄分组:");
        for (int i = 0; i < groupedByAge.size(); i++) {
            System.out.println("组 " + (i + 1) + ": " + groupedByAge.get(i));
        }
    }
}

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return name + "(" + age + ")";
    }
}

数据结构:

运行结果:

相关推荐
圆山猫6 小时前
[Virtualization](四):Linux KVM/RISC-V 的 vCPU 运行路径
java·linux·risc-v
城管不管6 小时前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
IT小白杨7 小时前
从环境制备到自动化工作流:多账号运营的工程化架构拆解
java·经验分享·自动化·安全架构·指纹浏览器
豆瓣鸡7 小时前
算法日记 - Day3
java·开发语言·算法
白白白小纯7 小时前
算法篇—反转链表
c语言·数据结构·算法·leetcode
萧瑟余晖7 小时前
Java深入解析篇九之NIO详解
java·网络·nio
The Chosen One9858 小时前
高进度算法模板速记(待完善)
java·前端·算法
极光代码工作室10 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
Leighteen10 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
阿米亚波11 小时前
【C++ STL】std::unordered_multimap
开发语言·数据结构·c++·笔记·stl