Close

Java Arrays - How to remove elements after a specific element in an array?

[Last Updated: Oct 30, 2025]

Java Arrays Java 


It can be accomplished by using Arrays.copyOfRange() as shown in this example:

package com.logicbig.example;

import java.util.Arrays;

public class ArrayRemoveAllAfter {
public static void main(String[] args) {
String[] anArray = {"one", "two", "three", "four", "five"};
System.out.println("-- original array --");
System.out.println(Arrays.toString(anArray));

System.out.println("-- removing after 'three' inclusively --");
String[] newArray = removeAfter(anArray, "three", true);
System.out.println(Arrays.toString(newArray));

System.out.println("-- removing after 'three' not inclusively --");
String[] newArray2 = removeAfter(anArray, "three", false);
System.out.println(Arrays.toString(newArray2));

System.out.println("-- removing after 'five' (last element) inclusively --");
String[] newArray3 = removeAfter(anArray, "five", true);
System.out.println(Arrays.toString(newArray3));

System.out.println("-- removing after 'five' (last element) not inclusively --");
String[] newArray4 = removeAfter(anArray, "five", false);
System.out.println(Arrays.toString(newArray4));

System.out.println("-- removing after 'one' (first element) inclusively --");
String[] newArray5 = removeAfter(anArray, "one", true);
System.out.println(Arrays.toString(newArray5));

System.out.println("-- removing after 'one' (first element) not inclusively --");
String[] newArray6 = removeAfter(anArray, "one", false);
System.out.println(Arrays.toString(newArray6));

}

public static <T> T[] removeAfter(T[] array, T target, boolean inclusive) {
for (int i = 0; i < array.length; i++) {
if (array[i].equals(target)) {
if (inclusive) {
return Arrays.copyOfRange(array, 0, i);
} else {
return Arrays.copyOfRange(array, 0, i + 1);

}
}
}
return array.clone();
}
}

Output

-- original array --
[one, two, three, four, five]
-- removing after 'three' inclusively --
[one, two]
-- removing after 'three' not inclusively --
[one, two, three]
-- removing after 'five' (last element) inclusively --
[one, two, three, four]
-- removing after 'five' (last element) not inclusively --
[one, two, three, four, five]
-- removing after 'one' (first element) inclusively --
[]
-- removing after 'one' (first element) not inclusively --
[one]




See Also