I am trying to perform the operation using the ForEach
in Java 8 by combining the removeIf
method. But I am getting the Error.
I am not able to combine the forEach
and removeIf
in the following program:
public class ForEachIterator {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
ints.add(i);
}
System.out.println(ints);
// Getting the Error in next line
ints.forEach(ints.removeIf(i -> i%2 ==0));
System.out.println(ints);
}
}
There's no need for the forEach
, the Lambda expression will work on all elements of the set
ints.removeIf(i -> i%2==0)
removeIf: "Removes all of the elements of this collection that satisfy the given predicate"
Simply...
For each element (i
) in the set (ints
), remove it if (removeIf
) the predicate (i%2==0
) is true for this element (i
). This will act on the original set and return true if any elements where removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With