简体   繁体   English

Java中的Streams,无法想出这段代码

[英]Streams in Java, can't figure this code out

I've found the following code snippet: 我找到了以下代码片段:

Function<Integer, Predicate<Integer>> smallerThan = x -> y -> y < x;
List<Integer> l = Arrays.asList(5, 6, 7, 23, 4, 5645,
    6, 1223, 44453, 60182, 2836, 23993, 1);

List<Integer> list2 = l.stream()
    .filter(smallerThan.apply(l.get(0)))
    .collect(Collectors.toList());

System.out.println(list2);

As output I receive: 作为输出我收到:

[4, 1]

How does the smallerThan function in this example work, considering that we only pass one parameter smallerThan.apply(l.get(0)) ? 考虑到我们只传递一个参数smallerThan.apply(l.get(0)) ,这个例子中的smallerThan函数如何工作?

smallerThan is a Function that accepts a single Integer and returns a Predicate<Integer> (a Predicate<Integer> is a function that accepts a single Integer and returns a boolean ). smallerThan是一个Function接受单个Integer ,并返回一个Predicate<Integer> (一个Predicate<Integer>是接受单个的函数Integer ,并返回一个boolean )。

smallerThan.apply(l.get(0)) returns a Predicate<Integer> that looks like this: smallerThan.apply(l.get(0))返回一个如下所示的Predicate<Integer>

y -> y < l.get(0)

ie it returns true if the input passed to it is smaller than l.get(0) . 即如果传递给它的输入小于l.get(0)则返回true

When you pass that Predicate to filter , your Stream pipeline keeps only the elements smaller than l.get(0) . 当您将Predicate传递给filter ,您的Stream管道仅保留小于l.get(0)的元素。

Your pipeline can be re-written as: 您的管道可以重写为:

List<Integer> list2 = l.stream()
    .filter(y -> y < l.get(0))
    .collect(Collectors.toList());

Since l.get(0) is 5 , your pipeline returns all the elements of the original list smaller than 5 . 由于l.get(0)5 ,因此管道将返回原始列表中小于5所有元素。

That is called "currying" and it was possible before Java 8 too via anonymous classes for example, but it was much more verbose. 这被称为“currying”,例如,在Java 8之前也可以通过匿名类来实现,但它更加冗长。 Ultimately, it's a Function that returns a Function and while not that spread in Java (yet), in other functional languages it is used quite heavily. 最终,它是一个Function ,它返回一个Function ,而不是在Java中传播(但是),在其他函数式语言中,它被大量使用。

The function smallerThan accepts a number and returns a Predicate object, in which case we apply this predicate to every element of the stream. 函数smallerThan接受一个数字并返回一个Predicate对象,在这种情况下,我们将这个谓词应用于流的每个元素。

So, l.get(0) will retrieve the first value of the list l which is (5) , we then pass it to the smallerThan function and this function returns a predicate with the criteria y -> y < x; 因此, l.get(0)将检索列表l的第一个值,即(5) ,然后我们将它传递给smallerThan函数,此函数返回一个谓词为y -> y < x;的谓词y -> y < x; which reads as "given a number, return true if it is less than 5" hence output is [4, 1] 读取为“给定一个数字,如果小于5则返回true”,因此输出为[4, 1]

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

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