Copy a java list with a limit of entries
12,148
Solution 1
List<Staff> second = new ArrayList<Staff>(staffs.subList(0, 20));
Solution 2
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));
Author by
johann
I am french and I live in Japan since 2007. I work as java/android/PHP developer mainly under centos and RH.
Updated on June 13, 2022Comments
-
johann almost 2 years
I would like to create a new
List<Object>
from a simpleList<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
-
johann over 12 yearsThank you. I didn't know the subList function.
-
johann over 12 yearsThank you for your comment ~ I'll try this next time !
-
karthik prasad over 5 yearsAlso with Guava, List<Staff> second = FluentIterable.from(staffs).limit(20).toList();