使用过滤器中的谓词对象的Java中的Lambda表达式

时间:2019-03-07 06:26:36

标签: java lambda

这是简单的代码,使用lambda表达式从整数列表中选择整数的随机子集。该函数正在做的是,遍历列表,并为每个元素调用一个随机布尔值。基于该元素被选择或丢弃。

public static List<Integer> getRandomSubsetUsingLambda(List<Integer> list) {
    List<Integer> randomSubset = new ArrayList<>();
    Random random = new Random();
    Predicate<Object> flipCoin = o -> {
        return random.nextBoolean();
    };

    randomSubset = list.stream().filter(flipCoin).collect(Collectors.toList());
    return randomSubset;
}

我的理解是,过滤器基于ta布尔值选择整数。但是我不知道那是怎么回事。这是否意味着无论何时调用flipCoin都会返回一个布尔值?

2 个答案:

答案 0 :(得分:0)

filter()将调用flipCoin,将流中的迭代值作为参数传递。 然后flipCoin将生成一个随机布尔值(忽略其参数值),如果为false,则将丢弃流中的迭代值。

即对于流中的每个元素,都会生成一个随机布尔值,并用于(随机)确定该元素是否被接受或丢弃。

答案 1 :(得分:0)

让我们选择一个包含三个元素List的{​​{1}}的实际示例

[1, 2, 3]

1

list.stream() .filter(flipCoin) // random.nextBoolean() returns true so 1 goes through .collect(Collectors.toList()); // 1 is waiting to be added to the list

2

list.stream() .filter(flipCoin) // random.nextBoolean() returns false and 2 is blocked .collect(Collectors.toList());

3

新的list.stream() .filter(flipCoin) // random.nextBoolean() returns true .collect(Collectors.toList()); // 3 is the last element of your stream so the list is created 包含List

基本上,每次调用[1, 3]时,都会为经过filter(flipCoin)的每个element执行以下块代码

Integer

基本上,您的流相当于以下代码块

public boolean test(Object o) {
    return random.nextBoolean();
}