[英]How to split a string array into small chunk arrays in java?
Below is the example of the code snippet which needs the help以下是需要帮助的代码片段示例
Example:例子:
[1,2,3,4,5]
1
, [1,2,3,4,5]
1
, [1,2,3,4,5]
2
, [1,2]
and [3,4]
and [5]
2
, [1,2]
和[3,4]
和[5]
3
, [1,2,3]
and [4,5]
3
, [1,2,3]
和[4,5]
4
, [1,2,3,4]
and [5]
4
, [1,2,3,4]
和[5]
Java (from comment): Java(来自评论):
int counter = 0;
for (int i=0; i<array.length; i++) {
if (count == chunksize) {
//do something and initialize
counter = 0;
}
counter++;
}
You can use Arrays.copyOfRange(int[] original, int from, int to)
The code could be something like this:你可以使用
Arrays.copyOfRange(int[] original, int from, int to)
代码可能是这样的:
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))));
}
Just stumbled upon this post after encountering the same question.在遇到同样的问题后偶然发现了这篇文章。 Here is how I solved it (I used
Arrays.copyOfRange()
:这是我解决它的方法(我使用了
Arrays.copyOfRange()
:
public static int[][] splitArray(int[] arrayToSplit, int chunkSize){
if(chunkSize<=0){
return null; // just in case :)
}
// first we have to check if the array can be split in multiple
// arrays of equal 'chunk' size
int rest = arrayToSplit.length % chunkSize; // if rest>0 then our last array will have less elements than the others
// then we check in how many arrays we can split our input array
int chunks = arrayToSplit.length / chunkSize + (rest > 0 ? 1 : 0); // we may have to add an additional array for the 'rest'
// now we know how many arrays we need and create our result array
int[][] arrays = new int[chunks][];
// we create our resulting arrays by copying the corresponding
// part from the input array. If we have a rest (rest>0), then
// the last array will have less elements than the others. This
// needs to be handled separately, so we iterate 1 times less.
for(int i = 0; i < (rest > 0 ? chunks - 1 : chunks); i++){
// this copies 'chunk' times 'chunkSize' elements into a new array
arrays[i] = Arrays.copyOfRange(arrayToSplit, i * chunkSize, i * chunkSize + chunkSize);
}
if(rest > 0){ // only when we have a rest
// we copy the remaining elements into the last chunk
arrays[chunks - 1] = Arrays.copyOfRange(arrayToSplit, (chunks - 1) * chunkSize, (chunks - 1) * chunkSize + rest);
}
return arrays; // that's it
}
chunkSize = 1
[1]
[2]
[3]
[4]
[5]
chunkSize = 2
[1, 2]
[3, 4]
[5]
chunkSize = 3
[1, 2, 3]
[4, 5]
chunkSize = 4
[1, 2, 3, 4]
[5]
chunkSize = 5
[1, 2, 3, 4, 5]
chunkSize = 6
[1, 2, 3, 4, 5]
If you don't mind importing Google Guava and converting to a List, there is a method for partitioning Lists:如果你不介意导入Google Guava并转换成List,这里有一个List分区的方法:
https://google.github.io/guava/releases/27.1-jre/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int- https://google.github.io/guava/releases/27.1-jre/api/docs/com/google/common/collect/Lists.html#partition-java.util.List-int-
The following may achieve the desired result:以下可能达到预期的结果:
List<Integer> listToBeSplit = Arrays.asList(sourceArray);
int chunkSize = 3;
Lists.partition(listToBeSplit, chunkSize);
Using pure Java 8:使用纯 Java 8:
public class Chunk {
public static void main(String[] args) {
int[] input = {1,2,3,4,78,999,-1,456};
int chunkSize = 3;
int[][] chunked = chunk(input, chunkSize);
Arrays.stream(chunked)
.map(Arrays::toString)
.forEach(System.out::println);
}
public static int[][] chunk(int[] input, int chunkSize) {
return IntStream.iterate(0, i -> i + chunkSize)
.limit((long) Math.ceil((double) input.length / chunkSize))
.mapToObj(j -> Arrays.copyOfRange(input, j, j + chunkSize > input.length ? input.length : j + chunkSize))
.toArray(int[][]::new);
}
}
[1, 2, 3]
[4, 78, 999]
[-1, 456]
Try this,尝试这个,
Iterate it and check to give the chunk size.迭代它并检查以给出块大小。
int chunkSize = userInput;
// iterate and check the condition // 迭代并检查条件
char[] resultArray = Arrays.copyOfRange(inputArray, start, end);
start = start + end; // check whether the start will exceeds the length of the array
import java.util.Arrays;
public class ArrayChunk {
public static void main(String[] args) {
int[] array = {1,2,3,4,5};
int[][] chunks1 = ArrayChunk(array, 1);
print(chunks1);
int[][] chunks2 = ArrayChunk(array, 2);
print(chunks2);
int[][] chunks3 = ArrayChunk(array, 3);
print(chunks3);
}
public static int[][] ArrayChunk(int[] array, int chunkSize) {
int numOfChunks = (int) Math.ceil((double) array.length / chunkSize);
int[][] output = new int[numOfChunks][];
for (int i = 0; i < numOfChunks; i++) {
int start = i * chunkSize;
int length = Math.min(array.length - start, chunkSize);
int[] temp = new int[length];
System.arraycopy(array, start, temp, 0, length);
output[i] = temp;
}
//
return output;
}
private static void print(int[][] output) {
//
System.out.println("======================");
for (int[] x : output)
System.out.println(Arrays.toString(x));
}
}
======================
[1]
[2]
[3]
[4]
[5]
======================
[1, 2]
[3, 4]
[5]
======================
[1, 2, 3]
[4, 5]
public static int[][] chunkArray(int[] array, int chunkSize) {
// first we need to get number of chunks by dividing length by chunkSize.
int numOfChunks = (int)Math.ceil((double)array.length / chunkSize);
// we declare 2d array to save in the chunks
int[][] output = new int[numOfChunks][];
for(int i = 0; i < numOfChunks; i++) {
int start = i * chunkSize;
int length = Math.min(array.length - start, chunkSize);
int[] temp = new int[length];
System.arraycopy(array, start, temp, 0, length);
output[i] = temp;
}
return output;
}
In general you could use Arrays.copyOfRange to copy一般来说,你可以使用Arrays.copyOfRange来复制
This should do the trick这应该可以解决问题
public static List<String> split(String string, int chunk) {
Pattern pattern = Pattern.compile("(([0-9]+,){" + (chunk - 1)
+ "}[0-9]+)|[0-9]+");
Matcher matcher = pattern.matcher(string);
List<String> result = new ArrayList<String>();
while (matcher.find())
result.add("[" + matcher.group() + "]");
return result;
}
Test code:测试代码:
for (int chunkSize = 1; chunkSize < 6; ++chunkSize) {
System.out.println("test for chunk size: " + chunkSize);
for (String string : split("[1,2,3,4,5]", chunkSize))
System.out.format("\t%s\n", string);
}
Output:输出:
test for chunk size: 1
[1]
[2]
[3]
[4]
[5]
test for chunk size: 2
[1,2]
[3,4]
[5]
test for chunk size: 3
[1,2,3]
[4]
[5]
test for chunk size: 4
[1,2,3,4]
[5]
test for chunk size: 5
[1,2,3,4,5]
public class ArrayChunk {
public static void main(String[] args) {
String[][] chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 2);
System.out.println("Array with chunk size 2");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 3);
System.out.println("Array with chunk size 3");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 4);
System.out.println("Array with chunk size 4");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
chunked = chunkArray("1,2,3,4,5,6,7,8,9".split(","), 5);
System.out.println("Array with chunk size 5");
Arrays.stream(chunked).forEach(strings -> System.out.println(String.join(",", strings)));
}
private static String[][] chunkArray(String[] array, int chunkSize) {
int chunkedSize = (int) Math.ceil((double) array.length / chunkSize); // chunked array size
String[][] chunked = new String[chunkedSize][chunkSize];
for (int index = 0; index < chunkedSize; index++) {
String[] chunk = new String[chunkSize]; // small array
System.arraycopy(array, index * chunkSize, chunk, 0, Math.min(chunkSize, array.length - index * chunkSize));
chunked[index] = chunk;
}
return chunked;
}
}
Output输出
Array with chunk size 2
1,2
3,4
5,6
7,8
9,null
Array with chunk size 3
1,2,3
4,5,6
7,8,9
Array with chunk size 4
1,2,3,4
5,6,7,8
9,null,null,null
Array with chunk size 5
1,2,3,4,5
6,7,8,9,null
for(int i=0;i<list.size();){
ArrayList<Integer>row = new ArrayList<Integer>();
int k=0;
while(k < chunksize){
chunk.add(list.get(i));
i++;
k++;
}
System.out.println(chunk);
nestedlist.add(chunk);
}
where list is a 1 dimension array and chunk is a nested array of size chunksize
其中 list 是一维数组,chunk 是大小为
chunksize
的嵌套数组
Easy way to do so,这样做的简单方法,
int loopcount = employeeList.size() / constCount;
int leftcount = employeeList.size() % constCount;
for (int i = 0; i < loopcount - 1; i++) {
//query.setParameterList("values"+i, employeeList.subList(tempCount, tempCount + constCount));
System.out.println(employeeList.subList(tempCount, tempCount + constCount));
tempCount = tempCount + 1000;
}
public class SplitArrayIntoChunks {
public static void main(String[] args) {
int[] in = {1,2,3,4,5};
chunks(in, 2);
}
private static void chunks(int[] in, int chunkSize) {
List<int[]> outList = new ArrayList<>();
int i = 0;
while (i < in.length) {
int[] out = Arrays.copyOfRange(in, i, Math.min(i + chunkSize, in.length));
outList.add(out);
out = new int[chunkSize + 1];
i += chunkSize;
}
for (int[] ol: outList) {
System.out.print("[");
Arrays.stream(ol).forEach(System.out::print);
System.out.println("]");
}
}
}
// Result: [12] [34] [5] // 结果:[12] [34] [5]
let array = [1, 2, 3, 4, 5, 6, 7, 8];
let idx = 0;
let count = 0;
let tempList = [];
let resultList = [];
let splitSize = 2
while (idx <= array.length)
{
tempList.push(array[idx++]);
count++;
if (count == splitSize)
{
resultList.push(tempList);
tempList = [];
count = 0;
}
}
if (!tempList.length)
{
resultList.push(tempList);
}
console.log(resultList);
This can be done in a few lines of code这可以在几行代码中完成
int i=0;
while (i<array.length) {
System.out.println(Arrays.toString(Arrays.copyOfRange(array, i, Math.min(array.length, i+chunkSize))));
i+=chunkSize;
}
Q.Split the array into chunks with a specified size? Q.将数组拆分为指定大小的块? Answer: public class SplitArray {
答案:公共类 SplitArray {
public static void main(String[] args) {
int[] original = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int splitSize = 3;
/* expected Output
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[9]
*/
List<int[]> list = splitArray(original, splitSize);
list.forEach(splitArray -> System.out.println(Arrays.toString(splitArray)));
}
public static List<int[]> splitArray(int[] array, int splitSize) {
List<int[]> result = new ArrayList<>();
int len=array.length;
int arr[] = null;
int size = splitSize;
int k=0;
for(int i=0;i<array.length;i++) {
if(k==0)
arr=new int[size];
arr[k]=array[i];
k++;
if(k>size-1) {
k=0;
result.add(arr);
len=len-size;
if(len<splitSize) {
size=len;
}
}
}
return result;
}
} }
you can use the methode toCharArray:您可以使用方法 toCharArray:
// Custom input string
String str = "12345678";
// Creating array and storing the array
// returned by toCharArray() method
char[] ch = str.toCharArray();
// Lastly printing the array elements
for (char c : ch) {
System.out.println(c);
}
see more: https://www.geeksforgeeks.org/convert-a-string-to-character-array-in-java/查看更多: https ://www.geeksforgeeks.org/convert-a-string-to-character-array-in-java/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.