[英]Lambda expressions in Java using predicate object in filter
This is simple code selecting a random subset of integers from a list of integers using lambda expressions.这是使用 lambda 表达式从整数列表中选择整数的随机子集的简单代码。 What the function is doing is, iterate through the list and for each element a random boolean value is called.
该函数正在做的是,遍历列表并为每个元素调用一个随机布尔值。 Based on that element is selected or discarded.
基于该元素被选择或丢弃。
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;
}
My understanding is that filter, based on ta boolean value selects the integers.我的理解是过滤器,基于 ta 布尔值选择整数。 But I didn't understand how is that happening.
但我不明白这是怎么发生的。 Does it mean that whenever flipCoin is called a boolean value is returned?
这是否意味着每当调用 flipCoin 时都会返回一个布尔值?
filter() will call to flipCoin passing as parameter the iterated value from the stream. filter() 将调用 flipCoin 作为参数传递来自流的迭代值。 Then flipCoin will generate a random boolean (ignoring the value of its parameter) and if false the iterated value from the stream will be discarded.
然后 flipCoin 将生成一个随机布尔值(忽略其参数的值),如果为 false,则流中的迭代值将被丢弃。
ie for each element in the stream a random boolean is generated and used to decide (randomly) if the element is accepted or discarded.即对于流中的每个元素,生成一个随机布尔值并用于(随机)决定该元素是被接受还是被丢弃。
Let's pick a practical example with a List
containing three elements [1, 2, 3]
让我们选择一个包含三个元素
[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
The new List
contains [1, 3]
新
List
包含[1, 3]
Basically, everytime filter(flipCoin)
is invoked, the following block code is executed for each element
going through it (here Integer
s)基本上,每次调用
filter(flipCoin)
,都会为通过它的每个element
执行以下块代码(此处为Integer
s)
public boolean test(Object o) {
return random.nextBoolean();
}
Basically, your stream is the equivalent of the following code block基本上,您的流相当于以下代码块
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.