0

I have an array list.I'd like to break the same into sub-list of fixed size.for example -

If my list size is 100.I want to have 30 elements in one list.So basically I'd like to create 4 sub-lists.What is the most optimized way to achieve this...I looked on the internet but most suggestions led to breaking an array list into subsists which didn't have an fixed size.any leads.pointers highly appreciated. Most Preferably,I'd like to have a service/method that does the job

4 Answers 4

3

If you are allowed to use third party libraries, Guava provides this as the single method Lists.partition, which is a constant time view.

Sign up to request clarification or add additional context in comments.

Comments

1
public static <T> List<List<T>> split( List<T> alist, int len ){
  List<List<T>> listOfLists = new ArrayList<>();
  int hi = 0;
  for( int lo = 0; lo < alist.size(); lo = hi ){
    hi = lo + len;
    if( hi > alist.size() ) hi = alist.size();
    listOfLists.add( new ArrayList<T>( alist.subList( lo, hi ) ) );
  }
  return listOfLists;
}

Comments

0
  • You can use List<E> subList(int fromIndex, int toIndex); to produce the sub lists.
  • Then you can convert each subList to an array, using <T> T[] toArray(T[] a);
  • Finally Arrays.asList will give you a fixed-sized list backed by that array.

3 Comments

@laune OP wanted fixed size sub-lists. Arrays.asList produces such lists. You need an array to use Arrays.asList.
The constructor from a Collection goes via an array, so that's moot - I prefer not to write what's already been written. And even if not, you could call trimToSize. (And it isn't really fixed, right?)
@laune In your code the ArrayLists you constructed are not fixed in size. If you use Arrays.asList, on the other hand, you will get a list that is really fixed (it doesn't return java.util.ArrayList, it returns java.util.Arrays.ArrayList which has a fixed length. add and remove are not supported)
0

I like the answer from @laune but if you use Java 8 this functional style approach could be used as well to avoid external looping.

public static <T> List<List<T>> splitJava8(List<T> alist, final int len) {
    return IntStream.range(0, alist.size()) // Iterate over the whole thing
            .filter(i -> i % len == 0) // Filter out every 'len' number
            .boxed() // Create a stream (instead of IntStream)
            .map(i -> alist.subList(i, Math.min(i + len, alist.size()))) // create sublists
            .collect(Collectors.toList()); // Collect the whole thing to a list of lists
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.