Java 8 - For Each 和 removeIf

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34992904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:37:25  来源:igfitidea点击:

Java 8 - For Each and removeIf

javalambda

提问by sathyendran a

I am trying to perform the operation using the ForEachin Java 8 by combining the removeIfmethod. But I am getting the Error.

我正在尝试ForEach通过组合removeIf方法使用Java 8 中的执行操作。但我收到错误。

I am not able to combine the forEachand removeIfin the following program:

我无法在以下程序中组合forEachremoveIf

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);
    }
}

回答by Ross Drew

There's no need for the forEach, the Lambda expression will work on all elements of the set

不需要forEach,Lambda 表达式将适用于集合的所有元素

ints.removeIf(i -> i%2==0)

removeIf: "Removes all of the elements of this collection that satisfy the given predicate"

removeIf: "移除这个集合中满足给定谓词的所有元素"

Simply...

简单地...

For each element (i) in the set (ints), remove it if (removeIf) the predicate (i%2==0) is true. This will act on the original set and return true if any elements where removed.

对于集合 ( i) 中的每个元素 ( ),ints如果 ( removeIf) 谓词 ( i%2==0) 为真,则将其删除。这将作用于原始集合并在删除任何元素时返回 true。