How to Create a Sub Array from Another Array in Java

Iteratively split an array to subarrays according to a given length

It seems you want to create all subarrays of a given length from an array.

You can do it by hand:

static double[][] subArrays(double[] arr, int k)
{
double[][] subArrs = new double[arr.length-k+1][k];

for(int i=0; i<subArrs.length; i++)
for(int j=0; j<k; j++)
subArrs[i][j] = arr[i+j];

return subArrs;
}

Or use the built-in method Arrays.copyOfRange:

static double[][] subArrays(double[] arr, int k)
{
double[][] subArrs = new double[arr.length-k+1][];

for(int i=0; i<subArrs.length; i++)
subArrs[i] = Arrays.copyOfRange(arr, i, i+k);

return subArrs;
}

Test:

double[] arr = {2, 4, 6, 30, 9};

for(double[] subArr : subArrays(arr, 3))
System.out.println(Arrays.toString(subArr));

Output:

[2.0, 4.0, 6.0]
[4.0, 6.0, 30.0]
[6.0, 30.0, 9.0]

The Java way to copy a subarray into an initialized array

You can use System.arraycopy :

System.arraycopy (sourceArray, sourceFirstIndex, outputArray, outputFirstIndex, numberOfElementsToCopy);

It does, however, throw IndexOutOfBoundsException is you provide invalid parameters.

If I understand the parameters in your example correctly, you need something like :

System.arraycopy (array, v, outputArray, w, lastIndex - v);

or

System.arraycopy (array, v, outputArray, w, lastIndex - v + 1);

if you want the element at lastIndex to be copied too.

Get only part of an Array in Java?

The length of an array in Java is immutable. So, you need to copy the desired part into a new array.

Use copyOfRange method from java.util.Arrays class:

int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);

startIndex is the initial index of the range to be copied, inclusive.

endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)

E.g.:

   //index   0   1   2   3   4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2); // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4); // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)

How to find the occurence of an array in another array? and returning indexes of the first array

One simple approach:

// 1) Convert array to String, for eg. [1,2,3,4] => "1234". 
// 2) Use Strings substring/lastIndexOf to find the correct index.

private static int findSubarrayPosition(int[] array, int[] subarray) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; i++) {
sb.append(array[i]);
}
String string = sb.toString();

sb = new StringBuilder();
for (int i = 0; i < subarray.length; i++) {
sb.append(subarray[i]);
}
String subString = sb.toString();

return string.lastIndexOf(subString);
}

Retrieve a segment of array in another array with a shallow copy and keeping the reference

Can I change the second array and the first array will change too?

There is no way for Java arrays to support that feature.

A Java array is an Object, so all arrays are independent objects, with their own memory structure for the array values.

(This is unlike C, where an array is done by pointer manipulation, so a second pointer can point into the memory sequence of an array already referenced by another pointer.)

If you want a sub-array of the first array, that is mapped such that changes to the sub-array is reflected in the main array, and vice-versa, you need something else.

One option is to use a List, and create the sub-list using subList(int fromIndex, int toIndex):

Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

If you already have an array, you can wrap the array with a list using Arrays.asList(T... a), then use the subList() as for any other list.

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.)

Note that List doesn't work for primitive types, so if your array is a primitive, you should use a Buffer of the appropriate type ( ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer).

E.g. for an int[], create the buffer using IntBuffer.wrap(int[] array, int offset, int length):

Wraps an int array into a buffer.

The new buffer will be backed by the given int array; that is, modifications to the buffer will cause the array to be modified and vice versa.

If you always access the array through the IntBuffer, by using IntBuffer.wrap(int[] array) to wrap the full array, your code could use either IntBuffer and not know if it is accessing the full array or the sub-array.

Find an array inside another larger array

The requirement of "using just core Java API's" could also mean that they wanted to see whether you would reinvent the wheel. So in addition to your own implementation, you could give the one-line solution, just to be safe:

public static int findArray(Integer[] array, Integer[] subArray)
{
return Collections.indexOfSubList(Arrays.asList(array), Arrays.asList(subArray));
}

It may or may not be a good idea to point out that the example given contains invalid array literals.

An array is subset of another array

Make a HashSet out of the superset array. Check if each of the elements of the subset array are contained in the HashSet. This is a very fast operation.

MongoDB Java - Update every sub-array element using another field value

The solution I finally came up with...

MongoCollection<Document> collection = database.getCollection("myCollection");
collection.find(
Filters.ne("someArray", Collections.emptyList()), MyDocumentRoot.class
).forEach(rootElement -> {
for(int i = 0; i < rootElement.getSomeArray().size(); i++){
Document document = collection.find(Filters.eq("_id", rootElement.getId())).first();
String color = document.getList("someArray", Document.class)
.get(i)
.getString("color");
collection.updateOne(
Filters.and(
Filters.eq("_id", rootElement.getId()),
Filters.eq("someArray._id", rootElement.getSomeArray().get(i).getId())
),
Updates.combine(
Updates.set("someArray.$.colors", Collections.singleton(color)),
Updates.unset("someArray.$.color")
)
);
}
});


Related Topics



Leave a reply



Submit