需求: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 + ")";
}
}
数据结构:

运行结果:
