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
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.
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.
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.
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));
List<Staff> second = new ArrayList<Staff>(staffs.subList(0, 20));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With