Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how can I split an ArrayList in multiple small ArrayLists?

Tags:

java

arraylist

How can I split an ArrayList (size=1000) in multiple ArrayLists of the same size (=10) ?

ArrayList<Integer> results; 
like image 344
aneuryzm Avatar asked May 24 '10 07:05

aneuryzm


People also ask

How can I split an ArrayList in multiple small ArrayLists?

You can use the chunk method from Eclipse Collections: ArrayList<Integer> list = new ArrayList<>(Interval. oneTo(1000)); RichIterable<RichIterable<Integer>> chunks = Iterate. chunk(list, 10); Verify.

How do you split a list into evenly sized chunks in Java?

array_split() is a numpy method that splits a list into equal sized chunks.


1 Answers

You can use subList(int fromIndex, int toIndex) to get a view of a portion of the original list.

From the API:

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations supported by this list.

Example:

List<Integer> numbers = new ArrayList<Integer>(     Arrays.asList(5,3,1,2,9,5,0,7) );  List<Integer> head = numbers.subList(0, 4); List<Integer> tail = numbers.subList(4, 8); System.out.println(head); // prints "[5, 3, 1, 2]" System.out.println(tail); // prints "[9, 5, 0, 7]"  Collections.sort(head); System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7]"  tail.add(-1); System.out.println(numbers); // prints "[1, 2, 3, 5, 9, 5, 0, 7, -1]" 

If you need these chopped lists to be NOT a view, then simply create a new List from the subList. Here's an example of putting a few of these things together:

// chops a list into non-view sublists of length L static <T> List<List<T>> chopped(List<T> list, final int L) {     List<List<T>> parts = new ArrayList<List<T>>();     final int N = list.size();     for (int i = 0; i < N; i += L) {         parts.add(new ArrayList<T>(             list.subList(i, Math.min(N, i + L)))         );     }     return parts; }   List<Integer> numbers = Collections.unmodifiableList(     Arrays.asList(5,3,1,2,9,5,0,7) ); List<List<Integer>> parts = chopped(numbers, 3); System.out.println(parts); // prints "[[5, 3, 1], [2, 9, 5], [0, 7]]" parts.get(0).add(-1); System.out.println(parts); // prints "[[5, 3, 1, -1], [2, 9, 5], [0, 7]]" System.out.println(numbers); // prints "[5, 3, 1, 2, 9, 5, 0, 7]" (unmodified!) 
like image 96
polygenelubricants Avatar answered Sep 17 '22 07:09

polygenelubricants