Java 8 - 懒惰评估?(Java 8 - Lazy Evaluation?)
当我发现自己对于Streams API如何对循环方法的命令性进行懒惰评估时,我正在浏览Streams Video。
这是典型的for循环代码,它检查第一个大于3的数字,甚至,然后它只是打印并返回。
List<Integer> arr = Arrays.asList(1, 2, 3, 5, 4, 6, 7, 8, 9); for (int i : arr) { System.out.println(" Checking if is Greater: " + i); if (i > 3) { System.out.println("checking if is Even " + i); if (i % 2 == 0) { System.out.println(i * 2); break; } } }
这里是预期的输出:
Checking if is Greater: 1 Checking if is Greater: 2 Checking if is Greater: 3 Checking if is Greater: 5 Checking if is Even 5 Checking if is Greater: 4 Checking if is Even 4 8
现在使用Streams API的代码相同:
arr.stream() .filter(Lazy::isGreater) .filter(Lazy::isEven) .map(Lazy::doubleIt) .findFirst();
它也以同样的方式评估。 那么
filter()
如何提供一些我们用传统for循环无法获得的东西呢?I was going through a Streams Video when I found myself confused as to how Streams API was giving lazy evaluation over the imperative for loop approach.
Here's the typical for loop code which checks for the first number that is greater than three and even, it then simply prints it and returns.
List<Integer> arr = Arrays.asList(1, 2, 3, 5, 4, 6, 7, 8, 9); for (int i : arr) { System.out.println(" Checking if is Greater: " + i); if (i > 3) { System.out.println("checking if is Even " + i); if (i % 2 == 0) { System.out.println(i * 2); break; } } }
Here the expected output:
Checking if is Greater: 1 Checking if is Greater: 2 Checking if is Greater: 3 Checking if is Greater: 5 Checking if is Even 5 Checking if is Greater: 4 Checking if is Even 4 8
Now here's the same code using Streams API:
arr.stream() .filter(Lazy::isGreater) .filter(Lazy::isEven) .map(Lazy::doubleIt) .findFirst();
It too evaluates the same way. So how is
filter()
providing something different which we can't get using the traditional for loops?
原文:https://stackoverflow.com/questions/33720757
最满意答案
我会做或多或少做
Array.from
工作 ,但检查length
的类型而不是总是转换它:const itemsOrSingle = items => { const iteratorFn = items[Symbol.iterator] if (iteratorFn) { return Array.from(iteratorFn.call(items)) } const length = items.length if (typeof length !== 'number') { return [items] } const result = [] for (let i = 0; i < length; i++) { result.push(items[i]) } return result }
I’d do more or less what
Array.from
does, but check the type oflength
instead of always converting it:const itemsOrSingle = items => { const iteratorFn = items[Symbol.iterator] if (iteratorFn) { return Array.from(iteratorFn.call(items)) } const length = items.length if (typeof length !== 'number') { return [items] } const result = [] for (let i = 0; i < length; i++) { result.push(items[i]) } return result }
相关问答
更多-
在数组迭代期间检查,如果当前元素是最后一个元素(Checking during array iteration, if the current element is the last element)[2023-10-02]
你可以使用PHP的end() $array = array('a' => 1,'b' => 2,'c' => 3); $lastElement = end($array); foreach($array as $k => $v) { echo $v . '
'; if($v == $lastElement) { // 'you can do something here as this condition states it just entered last el ... -
您尝试为iterable每个Iterable执行一些操作。 如果iterable是可Iterable extends Iterable> Iterable extends Iterable> (即它会遍历其他Iterable对象)。 但是因为你没有为参数指定一个类型参数,所以你只知道它会遍历某种对象(即基类型Object可用)。 你应该试试这个: for (Object o : iterable) { System.out.println(o); } 当大声读出时,其读作“对于每个Obj ...
-
您的add方法获取一个新的Iterator并多次调用it.hasNext() 。 它从不调用it.next() ,因此Iterator一直指向数组的第一个元素,而hasNext()永远不会返回false(假设数组不为空)。 Your add method obtains a new Iterator and calls it.hasNext() multiple times. It never calls it.next(), so the Iterator keeps pointing on the fi ...
-
使用itertools配方consume来跳过n元素: def consume(iterator, n): "Advance the iterator n-steps ahead. If n is none, consume entirely." # Use functions that consume iterators at C speed. if n is None: # feed the entire iterator into a zero-length d ...
-
我会做或多或少做Array.from工作 ,但检查length的类型而不是总是转换它: const itemsOrSingle = items => { const iteratorFn = items[Symbol.iterator] if (iteratorFn) { return Array.from(iteratorFn.call(items)) } const length = items.length if (typeof lengt ...
-
当你调用.equals(...)你调用了一个对象的方法。 如果为null,则没有方法。 因此null检查如下: if (myArray[position] == null) { .... } When you call .equals(...) you call a method of the object. If it is null, it has no method. Therefore null check like this: if (myArray[position] == null ...
-
给定可迭代,以概率p独立选择每个元素(Given iterable, select each element independently with probability p)[2023-12-31]
直到第一次成功的伯努利试验的数量由几何分布表示。 因此,您可以使用它来生成要使用numpy.random.geometric跳过的项目数: import itertools import numpy def binomial_choice(L, p): iterator = iter(L) while True: to_skip = numpy.random.geometric(p) - 1 yield next(itertools.islice(itera ... -
boolean语句上的分支应用于iterable的每个元素(Branch on boolean statement applied to each element of an iterable)[2021-12-11]
你可以使用any : >>> mylist = [1, 2, 3] >>> any(x > 4 for x in mylist) False >>> any(x % 2 == 0 for x in mylist) True if any(my_condition(x) for x in mylist): .... 注意:使用生成器表达式而不是列表推导,您不需要评估所有项目。 You can use any: >>> mylist = [1, 2, 3] >>> any(x > 4 for x i ... -
检查元素是否存在(Checking if an element exist)[2022-05-27]
is-member2不等于is-memeber2 。 检查你的拼写。 is-member2 does not equal is-memeber2. Check your spelling. -
您只需要更改MapperUtils public class MapperUtils { @FirstElement public String firstEmailAddress(List
in) { if (in != null && !in.isEmpty()) { return in.get(0).getEmailAddress(); } else { return nul ...