I have a list of integers in order. I want to get groups of consecutive integers in the form of arrays with the 1st and last integer for each group.
For example, for (2,3,4,5,8,10,11,12,15,16,17,18,25) I want to get a list with these arrays: [2,5] [8,8] [10 , 12] [15.18] [25.25]
Here is my code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MyRangesTest {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(2,3,4,5,8,10,11,12,15,16,17,18,25);
System.out.println("list:" + list);
List<Integer> sublistsStarsAndEnds= new ArrayList<>();
sublistsStarsAndEnds.add(list.get(0));
for (int i=1; i<list.size()-1; i++){
if (list.get(i)>1+list.get(i-1)){
sublistsStarsAndEnds.add(list.get(i-1));
sublistsStarsAndEnds.add(list.get(i));
}
}
sublistsStarsAndEnds.add(list.get(list.size()-1));
System.out.println("sublistsStarsAndEnds: " + sublistsStarsAndEnds);
List<Integer[]> ranges= new ArrayList<>();
for (int i=0; i<sublistsStarsAndEnds.size()-1; i=i+2){
Integer[] currentrange=new Integer[2];
currentrange[0]=sublistsStarsAndEnds.get(i);
currentrange[1]=sublistsStarsAndEnds.get(i+1);
ranges.add(currentrange);
}
String rangestxt="";
for (int i=0; i<ranges.size(); i++){
rangestxt=rangestxt+ranges.get(i)[0]+ " " + ranges.get(i)[1]+ " ";
}
System.out.println("ranges: " + rangestxt);
}
}
This code works in the general case for what I want, but when the last sequence has only 1 integer, it cannot get the correct result.
For example, when using this list: (2,3,4,5,8,10,11,12,15,16,17,18,25) instead of getting ranges [2.5] [8, 8] [10, 12] [15,18] [25,25] we get the ranges [2,5] [8,8] [10,12] [15,25].
, . sublistsStarsAndEnds. [2, 5, 8, 8, 10, 12, 15, 15, 25, 25] [2, 5, 8, 8, 10, 12, 15, 25].
, .
, ?
P.S. - , , Python . Python, .