Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string array into small chunk arrays in java?

Tags:

java

Below is the example of the code snippet which needs the help

Example:

[1,2,3,4,5] 
  • if the chunk size is 1, [1,2,3,4,5]
  • if the chunk size is 2, [1,2] and [3,4] and [5]
  • if the chunk size is 3, [1,2,3] and [4,5]
  • if the chunk size is 4, [1,2,3,4] and [5]

Java (from comment):

int counter = 0; for (int i=0; i<array.length; i++) {   if (count == chunksize) {     //do something and initialize     counter = 0;   }   counter++;  } 
like image 656
user2323036 Avatar asked Jan 09 '15 09:01

user2323036


People also ask

Can you split a string array in Java?

Split() String method in Java with examples. The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.

How do you subdivide an array in Java?

Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.

Can you split a string array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

You can use Arrays.copyOfRange(int[] original, int from, int to) The code could be something like this:

int chunk = 2; // chunk size to divide for(int i=0;i<original.length;i+=chunk){     System.out.println(Arrays.toString(Arrays.copyOfRange(original, i, Math.min(original.length,i+chunk)))); }           
like image 104
Reza Avatar answered Sep 20 '22 07:09

Reza