Java获取列表中多组连续数据
Java中有时需要把相邻连续的元素取出,获取列表中多组连续数据
如[1,2,4,5,6,7,16,17,18,26],,这里需要把相邻连续的数分组取出,取出结果为:
[[1, 2], [4, 5, 6, 7], [16, 17, 18], [26]],下面为Java的一个实现方法。
// 实现方法
/**
* 获取列表中多组相邻连续数据
* @param list 原数据
* @return 多组连续数据
*/
public static List<List<Integer>> getSerialNumList(List<Integer> list) {
//收集的总的连续列表
List<List<Integer>> collect = new ArrayList<>();
//每个收集的连续临时列表
List<Integer> tempList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
int current = list.get(i);
if (i < list.size() - 1) {
int next = list.get(i + 1);
if (current + 1 == next) {
tempList.add(current);
} else {
//不连续时,把最后一个数放进去之前的临时列表
tempList.add(current);
collect.add(tempList);
//同时把临时列表置空
tempList = new ArrayList<>();
}
} else {
//最后一个元素时,放入最后一个临时列表中
tempList.add(current);
collect.add(tempList);
}
}
System.out.println(collect);
return collect;
}
// 输入一些数据进行测试
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1,2,4,5,6,7,16,17,18,26);
getSerialNumList(list);
}
// 输出结果:
[[1, 2], [4, 5, 6, 7], [16, 17, 18], [26]]
链接: link.
图片: