[Java] How to remove a given string from an array?
I want to remove a specific string from an array, how can I do that in Java?
1 Answer
4 years ago by Eleven
We can stream on an array and use filter to eliminate the element and convert the stream to a new Array. Following code shows how to do that.
import java.util.Arrays;
public class JavaArrays {
public static void main(String[] args) {
String[] colors = { "blue", "red", "green", "yellow" };
String colorToRemove = "red";
String[] newArray = Arrays.stream(colors).filter(ele -> !ele.equals(colorToRemove)).toArray(String[]::new);
System.out.println(Arrays.toString(newArray));
}
}
Output:
[blue, green, yellow]
Try this code online here: https://onecompiler.com/java/3xmtayxcg
4 years ago by Karthik Divi