需求:对一个数组按顺序进行分组
起因:
今天领导突然来了个需求,需要发送 2000 多条短信,但是第三方接口只能一次调用 200 条短信,情况紧急,但是我又不想一个个的弄,于是想能不能分组进行发送,在百度上搜了半天,看到的方法也很多,
但也很复杂,终于决定还是自己写一个吧 😥
实现过程:
首先设定两个变量
1.需要分组的数组 String[] elements
2.每个组的元素的数量 int gc
这样就可以计算总共的组数 count = elements.length/gc
count 有两种情况
一种能被整除为 count
不能被整除为 count+1
代码:
private static List<String[]> groupBySequence(int gc, String[] elements){ List<String[]> list = new ArrayList<>(); int count = elements.length/gc; int mod = elements.length%gc; if (mod != 0) count++; for (int i = 0;i<count;i++){ String[] arr; if (i == (count-1)){ if (mod != 0){ int temp = 0; arr = new String[mod]; for (int j = i*gc; j<(i*gc)+mod;j++){ arr[temp] = elements[j]; temp++; } } else { int temp = 0; arr = new String[gc]; for (int j=i*gc;j<gc*(i+1);j++){ arr[temp] = elements[j]; temp++; } } } else { int temp = 0; arr = new String[gc]; for (int j=i*gc;j<gc*(i+1);j++){ arr[temp] = elements[j]; temp++; } } list.add(arr); } return list; }
调用方法:
public static void main(String[] args) { String[] arrays = {"杨过","小龙女","令狐冲","任盈盈","郭靖","黄蓉","张无忌","赵敏","段誉","王语嫣","鸠摩智"}; int gc = 2; List list = ArraysUtils.groupBySequence(gc, arrays); System.out.println(JSONObject.toJSONString(list));
}
运行结果
[["杨过","小龙女"],["令狐冲","任盈盈"],["郭靖","黄蓉"],["张无忌","赵敏"],["段誉","王语嫣"],["鸠摩智"]]
情况紧急所以写的很随意,过几天再回来优化 ☺️
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于