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;
}
public static void main(String[] args) {
List<List<Integer>> res = groupBy(Arrays.asList(14, 1, 2, 3, 4, 7, 11, 12, 13, 17, 18));
System.out.println(res);
}
|