johann
johann

Reputation: 1135

Copy a java list with a limit of entries

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

Answers (2)

Arend von Reinersdorff
Arend von Reinersdorff

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

Brigham
Brigham

Reputation: 14544

List<Staff> second = new ArrayList<Staff>(staffs.subList(0, 20));

Upvotes: 15

Related Questions