Java 连续数字分组
该方法是针对集合中连续的数字进行分组:
public static List<List<Integer>> groupBy(List<Integer> data) {
if (data == null) {
return new ArrayList<>();
}
Collections.sort(data);
List<List<Integer>> result = new ArrayList<>();
List<Integer> group = null;
for (Integer value : data) {
if (group == null || group.get(group.size() - 1) + 1 != value) {
group = new ArrayList<>();
result.add(group);
}
group.add(value);
}
return result;
}