Reputation: 1135
I would like to create a new List<Object>
from a simple List<Object>
only for the 20 first entries.
//my first array
List<Staff> staffs = new ArrayList<Staff>();
staffs.add(new Staff(...));
staffs.add(new Staff(...));
staffs.add(new Staff(...));
staffs.add(new Staff(...));
List<Staff> second = magicMethodForClone(staffs,20);
I'd like to know if a method like magicMethodForClone
exists or not.
Thank you
Upvotes: 11
Views: 15696
Reputation: 4233
List.subList(0, 20)
will throw an Exception if your list contains less than 20 elements.
With Java 8:
You can use Stream.limit():
List<Staff> second = staffs.stream().limit(20).collect(Collectors.toList());
With Java 7 or lower:
You can use Guava's Iterables.limit() to get all available elements but no more than 20:
List<Staff> second = Lists.newArrayList(Iterables.limit(staffs, 20));
Upvotes: 34
Reputation: 14544
List<Staff> second = new ArrayList<Staff>(staffs.subList(0, 20));
Upvotes: 15