I have a list of numbers and I want to make sublists,
where each sublist begins at 1 and ends at 3.
This is my list :
List<String> items = [ '1', '2', '3', '1', '2', '4', '3', '1', '3' ];
This is what I want to get : listOfLists = [[1,2,3], [1,2,4,3], [1,3]]
4
Answers
You can iterate through your list like this:
You initialize
listOfLists
to store the sublists.Iterating through the original list items:
When you encounter ‘1’, you set the
startIndex
to the current index.When you encounter ‘3’, you set the
endIndex
to the current index.If you find ‘1’ again before finding ‘3’, it means a new sublist has started, so you add the previous sublist to
listOfLists
.In the end you add the last sublist if it ends with ‘3’.
A oneliner way to do it is
EDIT:
I learned about
splitBetween
after my first answer. This will make it even more concise:This does require the
collection
package so you also need to doI added a couple of tests based on guesses:
You can also use the sublist() method to create a sublist of the entire list, starting at a certain index:
List numbers = [1, 2, 3, 4, 5];
List sublist = numbers.sublist(2);
print(sublist); // [3, 4, 5]