java 给list对象根据给定条数进行分组工具类
java 给list对象根据给定条数进行分组工具类
下面是一个示例的工具类,可以根据给定的条数对Student对象的List进行分组:
import java.util.ArrayList;
import java.util.List;
public class StudentGroupUtil {
public static List<List<Student>> groupStudents(List<Student> students, int groupSize) {
List<List<Student>> result = new ArrayList<>();
int size = students.size();
int groupCount = (size + groupSize - 1) / groupSize; // 计算分组个数
for (int i = 0; i < groupCount; i++) {
int start = i * groupSize; // 计算起始索引
int end = Math.min((i + 1) * groupSize, size); // 计算结束索引
List<Student> group = students.subList(start, end); // 获取子列表作为分组
result.add(group);
}
return result;
}
}
使用示例:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 18));
students.add(new Student("Bob", 20));
students.add(new Student("Charlie", 22));
students.add(new Student("David", 24));
students.add(new Student("Emma", 26));
List<List<Student>> groups = StudentGroupUtil.groupStudents(students, 2);
for (List<Student> group : groups) {
System.out.println("Group:");
for (Student student : group) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
System.out.println();
}
}
}
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
输出结果:
Group:
Name: Alice, Age: 18
Name: Bob, Age: 20
Group:
Name: Charlie, Age: 22
Name: David, Age: 24
Group:
Name: Emma, Age: 26