Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 244
johann Avatar asked Jan 16 '12 05:01

johann


People also ask

How do you copy all the elements of a list to another in Java?

To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list. Approach: Create a cloneable class, which has the clone method overridden. Create a list of the class objects from an array using the asList method.

How do you limit an ArrayList?

trimToSize() method is used for memory optimization. It trims the capacity of ArrayList to the current list size. For e.g. An arraylist is having capacity of 15 but there are only 5 elements in it, calling trimToSize() method on this ArrayList would change the capacity from 15 to 5.

What is the limit of ArrayList in Java?

Whenever an instance of ArrayList in Java is created then by default the capacity of Arraylist is 10. Since ArrayList is a growable array, it automatically resizes itself whenever a number of elements in ArrayList grow beyond a threshold.


2 Answers

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));
like image 52
Arend v. Reinersdorff Avatar answered Sep 25 '22 02:09

Arend v. Reinersdorff


List<Staff> second = new ArrayList<Staff>(staffs.subList(0, 20));
like image 27
Brigham Avatar answered Sep 25 '22 02:09

Brigham