Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - For Each and removeIf

Tags:

java

lambda

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);
    }
}
like image 960
Sathyendran a Avatar asked Jan 25 '16 12:01

Sathyendran a


1 Answers

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.

like image 140
Ross Drew Avatar answered Oct 19 '22 18:10

Ross Drew