split Array By Size - Java java.lang

Java examples for java.lang:String Split

Description

split Array By Size

Demo Code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] argv) {
    String[] arr = new String[] { "1", "abc", "level", null, "java2s.com", "asdf 123" };
    int size = 2;
    System.out.println(splitArrBySize(arr, size));
  }/*from  w  w w.  java2s. c om*/

  public static List<String[]> splitArrBySize(String[] arr, int size) {
    List<String[]> list = new ArrayList<String[]>();
    if (arr != null) {
      int from = 0;
      int length = arr.length;
      int to = size < length ? size : length;
      String[] tmp;
      while (from < length) {
        tmp = Arrays.copyOfRange(arr, from, to);
        list.add(tmp);
        from = to;
        to = (to + size) < length ? (to + size) : length;
      }
    }
    return list;
  }
}

Related Tutorials