user2380243
user2380243

Reputation: 3

Divide array list into sub list of fixed size

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

Upvotes: 0

Views: 2546

Answers (4)

wassgren
wassgren

Reputation: 19201

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
}

Upvotes: 0

laune
laune

Reputation: 31290

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;
}

Upvotes: 1

Eran
Eran

Reputation: 393771

  • 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.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198023

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

Upvotes: 3

Related Questions