繁体   English   中英

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

[英]Lambda expressions in Java using predicate object in filter

这是使用 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 时都会返回一个布尔值?

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

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

让我们选择一个包含三个元素[1, 2, 3]List的实际示例

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 s)

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

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

List<Integer> newList = new ArrayList<>();
for (Integer i : list) {
    boolean shouldBeAddedToNewList = random.nextBoolean();
    if (shouldBeAddedToNewList) {
        newList.add(i);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM