Finding a sub array within in an array can be achieved using several methods in Java. It gets a bit trickier when we want to find every occurrence of the sub array in the array.
Let’s start with finding one single occurrence of the sub array. We can use JAVA Collections for this, transforming both the sub array and the Array to a List;
/* To find a single occurrence of a subarray in an array */
String[] array = {"welcome","to","code1","tech"};
String[] subArray = {"code1","tech"};
Integer foundPosition = Collections.indexOfSubList(Arrays.asList(array), Arrays.asList(subArray));
System.out.println("foundPosition: "+foundPosition);
This outputs a result of position 2.
If the sub array is not found, the result will be -1.
If we want to find multiple occurrences of the sub array in the array, we can form a loop;
String[] array = {"welcome","to","code1","tech","and","code1","tech","welcomes","you"};
String[] subArray = {"code1","tech"};
Integer searchPosition=0;
while (searchPosition < array.length) {
String[] subArray1 = Arrays.copyOfRange(array, searchPosition, array.length);
int newPositionFound = Collections.indexOfSubList(Arrays.asList(subArray1), Arrays.asList(subArray));
if (newPositionFound == -1) {
System.out.println("No further positions found");
break;
} else {
int originalPosition = searchPosition + newPositionFound;
System.out.println("new position found: " + originalPosition);
searchPosition = originalPosition + 1;
}//end else
}//end while
This outputs:
new position found: 2
new position found: 5
No further positions found
Here we use a new sub array (subArray1) using “Arrays.copyOfRange”. This is the array we search. The remainder of the code is calculating the original position by adding “newPositionFound” to the “originalPosition” to come up with our “searchPosition”.






