[Java] How to remove all elements from an array which are present in another array?
I want to remove all elements in an array with a condition, the condition is if the element present in another array, how can I do this in Java?
1 Answer
4 years ago by Eleven
Using streams we can iterate over the elemetns and use the filter to see if the element present in the other array, and create the filtered elements into a new Array.
Following code shows how to do that.
Note: In this example we are removing harshColors from allColors.
import java.util.Arrays;
public class JavaArrays {
public static void main(String[] args) {
String[] allColors = { "red", "gren", "blue", "orange", "maroon" };
String[] harshColors = { "red", "maroon" };
String[] filteredColors = Arrays.stream(allColors)
.filter(ele ->
Arrays.stream(harshColors)
.noneMatch(ele::equals))
.toArray(String[]::new);
System.out.println("Subarray is: " + Arrays.toString(filteredColors));
}
}
Output:
Filtered array is: [gren, blue, orange]
try online here: https://onecompiler.com/java/3xmsxj38h
4 years ago by Karthik Divi