Reputation: 21
I have an ArrayList with elements for example:
var x = [1,2,3,4,5,6];
how can I store only the first 3 [1,2,3] elements in another list?
Upvotes: 0
Views: 104
Reputation: 12703
You can use the take
function as @Christopher Moore
said
or the sublist
function
var x = [1, 2, 3, 4, 5, 6];
var usingTake = x.take(3).toList(); // 1,2,3
var usingSubList = x.sublist(0, 3); // 1,2,3
You can also use sublist
to take any portion of the list.
For example: Getting the last 3 elements will be like:
var x = [1, 2, 3, 4, 5, 6];
var usingSubList = x.sublist(x.length - 3, x.length);
Upvotes: 0
Reputation: 17141
Use the take
function:
var x = [1,2,3,4,5,6];
var y = x.take(3).toList();
Upvotes: 1