Reputation: 25
I am trying to split the Arraylist into numbers of Arraylists with the rule:
i
in arraylist is bigger than the value of index i+1
.For example, if there is an arraylist {6,7,8,3,9,10,1,4}
,
it should be stored as { {6,7,8}, {3,9,10}, {1,4} }
.
How can I do this one?
Upvotes: 1
Views: 1010
Reputation: 41
public static void splitList(ArrayList<Integer> input) {
ArrayList<ArrayList<Integer>> output = new ArrayList<ArrayList<Integer>>();
System.out.println("Input : "+input);
for (int count = 0; count < input.size(); count++) {
ArrayList<Integer> subList = new ArrayList<Integer>();
for (int index = count; index < input.size(); index++) {
if((index == input.size() - 1) || (input.get(index) > input.get(index + 1))){
subList.add(input.get(index));
count = index;
break;
}else {
subList.add(input.get(index));
}
}
output.add(subList);
}
System.out.println("Output : "+output);
}
Upvotes: 1
Reputation: 76
This code should work for you
List<Integer> mainList = new ArrayList<>();
List<List<Integer>> listOfLists = new ArrayList<>();
int listIndex = 0;
for (int i = 0; i < mainList.size(); i++) {
if (i == 0) {
listOfLists.add(new ArrayList<>());
} else if (mainList.get(i) < mainList.get(i - 1)) {
listOfLists.add(new ArrayList<>());
listIndex++;
}
listOfLists.get(listIndex).add(mainList.get(i));
}
Upvotes: 1
Reputation: 36
By looping through the original arraylist and using the sublist method the below code should solve your problem.
ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(6,7,8,3,9,10,1,4));
int indexToSplitFrom = 0;
for(int i = 0; i < numbers.size() - 1; i++){
System.out.println(numbers.get(i));
if(numbers.get(i) > numbers.get(i+1)){
lists.add(new ArrayList<>(numbers.subList(indexToSplitFrom, i + 1)));
indexToSplitFrom = i + 1;
}
}
lists.add(new ArrayList<>(numbers.subList(indexToSplitFrom, + numbers.size())));
Upvotes: 2