import java.util.ArrayList; import java.util.List; public class CollectionGroupUtil { public static List groupListByQuantity(List list, int quantity) { if (list == null || list.size() == 0) { return list; } if (quantity <= 0) { new IllegalArgumentException("Wrong quantity."); } List wrapList = new ArrayList(); int count = 0; while (count < list.size()) { wrapList.add(list.subList(count, (count + quantity) > list.size() ? list.size() : count + quantity)); count += quantity; } return wrapList; } }
import java.util.ArrayList; import java.util.List; import org.junit.Test; public class CollectionGroupUtilTest { /** * 大于分组数量的情况 */ @Test public void test() { List<String> allList = new ArrayList<String>(); for (int i = 1; i <= 504; i++) { allList.add(i + ""); } List<List<String>> groupList = CollectionGroupUtil.groupListByQuantity(allList, 50); int i = 0; List<String> list = null; for (int c = 0; c < groupList.size(); c++) { list = groupList.get(c); System.out.println("第" + (c + 1) + "组: "); for (String temp : list) { System.out.print(temp + ", "); } System.out.println(); } } /** * 小于分组数量的情况 */ @Test public void test2() { List<String> allList = new ArrayList<String>(); for (int i = 1; i <= 45; i++) { allList.add(i + ""); } List<List<String>> groupList = CollectionGroupUtil.groupListByQuantity(allList, 50); int i = 0; List<String> list = null; for (int c = 0; c < groupList.size(); c++) { list = groupList.get(c); System.out.println("第" + (c + 1) + "组: "); for (String temp : list) { System.out.print(temp + ", "); } System.out.println(); } } /** * 集合只有一个记录的情况 */ @Test public void test3() { List<String> allList = new ArrayList<String>(); for (int i = 1; i <= 1; i++) { allList.add(i + ""); } List<List<String>> groupList = CollectionGroupUtil.groupListByQuantity(allList, 50); int i = 0; List<String> list = null; for (int c = 0; c < groupList.size(); c++) { list = groupList.get(c); System.out.println("第" + (c + 1) + "组: "); for (String temp : list) { System.out.print(temp + ", "); } System.out.println(); } } /** * 空集合的情况 */ @Test public void test4() { List<List<String>> groupList = CollectionGroupUtil.groupListByQuantity(null, 50); System.out.println(groupList); groupList = CollectionGroupUtil.groupListByQuantity(new ArrayList(), 50); System.out.println(groupList); } /** * 集合刚满一个分组的情况 */ @Test public void test5() { List<String> allList = new ArrayList<String>(); for (int i = 1; i <= 50; i++) { allList.add(i + ""); } List<List<String>> groupList = CollectionGroupUtil.groupListByQuantity(allList, 50); int i = 0; List<String> list = null; for (int c = 0; c < groupList.size(); c++) { list = groupList.get(c); System.out.println("第" + (c + 1) + "组: "); for (String temp : list) { System.out.print(temp + ", "); } System.out.println(); } } }