Copy list limit java list

I would like to create a new List<Object> from a simple List<Object> for only the first 20 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 would like to know if a method like magicMethodForClone .

thanks

+7
source share
2 answers
 List<Staff> second = new ArrayList<Staff>(staffs.subList(0, 20)); 
+11
source

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 Iterables.limit () to get all available elements, but no more than 20:

 List<Staff> second = Lists.newArrayList(Iterables.limit(staffs, 20)); 
+21
source

All Articles