Alex Rivera | Logout

Copy a java list with a limit of entries

Asked 2012-01-16T05:17:30.020
11

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

Edit
Report

2 Answers

34

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));
answered 2012-01-17T11:55:41.867
15
List<Staff> second = new ArrayList<Staff>(staffs.subList(0, 20));
answered 2012-01-16T05:20:42.330

Your Answer