平均等分List测试

2019-01-07 11:16:13
  1. import java.util.ArrayList;
  2. import java.util.List;
  3. /**
  4. * 平均等分List测试
  5. *
  6. * @author wangjing
  7. * @version 1.0 created 2018/12/19
  8. */
  9. public class AverageAssignListTest {
  10. public static void main(String[] args) {
  11. List<Integer> testList = new ArrayList<>();
  12. int num = 100;
  13. for (int i = 0; i < num; i++) {
  14. testList.add(i);
  15. }
  16. List<List<Integer>> list = averageAssign(testList, 101);
  17. for (List<Integer> bean : list) {
  18. System.out.println(bean.size());
  19. }
  20. }
  21. /**
  22. * 平均等分List
  23. *
  24. * @param allList
  25. * @return
  26. * @author wangjing
  27. * @date: 上午11:06 2018/12/19
  28. */
  29. public static <T> List<List<T>> averageAssign(List<T> allList, int num) {
  30. List<List<T>> resultList = new ArrayList<>();
  31. //计算余数
  32. int remainder = allList.size() % num;
  33. //计算商
  34. int number = allList.size() / num;
  35. //偏移量
  36. int offset = 0;
  37. if (num > allList.size()) num = allList.size();
  38. for (int i = 0; i < num; i++) {
  39. List<T> list = null;
  40. if (remainder > 0) {
  41. list = allList.subList(i * number + offset, (i + 1) * number + offset + 1);
  42. offset++;
  43. remainder--;
  44. } else {
  45. list = allList.subList(i * number + offset, (i + 1) * number + offset);
  46. }
  47. resultList.add(list);
  48. }
  49. return resultList;
  50. }
  51. }

0
2
0

添加评论

正在回复:
取消
0
0
2
0