在Java中,流循环有什么优势? [英] In Java, what are the advantages of streams over loops?

查看:197
本文介绍了在Java中,流循环有什么优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在接受采访时被问到这个问题,我不相信我能给出最好的答案。我提到你可以进行并行搜索,并且通过某些我无法记住的方法处理空值。现在我意识到我在想Optionals。我在这里想念的是什么?他们声称它的代码更好或更简洁,但我不确定我是否同意。

I was asked this at an interview and I'm not convinced I gave the best answer I could have. I mentioned that you can do a parallel search and that null values were handled by some means I couldn't remember. Now I realize I was thinking of Optionals. What am I missing here? They claim it's better or more concise code but I'm not sure I agree.

考虑到答案是多么简洁,看起来这毕竟不是一个问题。

Considering how succinctly it was answered, it seems that this wasn't too broad a question after all.

如果他们在面试中问这个问题,并且显然是这样,那么除了让它更难找到答案?我的意思是,你在找什么?我可以打破这个问题并解决所有子问题但是然后创建一个包含所有子项的链接的父问题......虽然看起来很傻。虽然我们在这里,但请举一个不太广泛的问题的例子。我知道没有办法只问这个问题的一部分,仍然得到一个有意义的答案。我可以用不同的方式问同一个问题。例如,我可以问流服务的目的是什么?或我什么时候使用流而不是for循环?或为什么要打扰流而不是循环?这些都是完全相同的问题。

If they are asking this question at interviews, and clearly they are, what purpose could breaking it down serve other than to make it harder to find an answer? I mean, what are you looking for? I could break down the question and have all the sub-questions answered but then create a parent question with links to all the subquestions... seems pretty silly though. While we are at it, please give me an example of a less broad question. I know of no way to ask only part of this question and still get a meaningful answer. I could ask exactly the same question in a different way. For example, I could ask "What purpose do streams serve?" or "When would I use a stream instead of a for loop?" or "Why bother with streams instead of for loops?" These are all exactly the same question though.

......还是被认为过于宽泛,因为有人给出了很长的多点答案?坦率地说,知情人士几乎可以解决任何问题。例如,如果您恰好是JVM的作者之一,那么当我们大多数人不能这样做时,您可能会整天谈论for循环。

...or is it considered too broad because someone gave a really long multi-point answer? Frankly anyone in the know could do that with virtually any question. If you happen to be one of the authors of the JVM, for example, you could probably talk about for loops all day long when most of us couldn't.

请编辑问题,将其限制为具有足够详细信息的特定问题,以确定适当的答案。避免一次提出多个不同的问题。请参阅如何向页面寻求帮助以澄清这个问题。

如下所述,已经给出了足够的答案,证明有一个并且很容易足以提供。

As noted below, an adequate answer has been given which proves that there is one and that it is easy enough to provide.

推荐答案

有趣的是,面试问题询问了优势,而没有提出不利因素,因为两者都有。

Interesting that the interview question asks about the advantages, without asking about disadvantages, for there are are both.

Streams是一种更具说明性的风格。或者更强烈的富有表现力的风格。在代码中声明你的意图可能被认为是更好的,而不是描述如何它已经完成:

Streams are a more declarative style. Or a more expressive style. It may be considered better to declare your intent in code, than to describe how it's done:

 return people
     .filter( p -> p.age() < 19)
     .collect(toList());

...非常清楚地表明你正在过滤列表中的匹配元素,而:

... says quite clearly that you're filtering matching elements from a list, whereas:

 List<Person> filtered = new ArrayList<>();
 for(Person p : people) {
     if(p.age() < 19) {
         filtered.add(p);
     }
 }
 return filtered;

说我正在做一个循环。循环的目的深埋在逻辑中。

Says "I'm doing a loop". The purpose of the loop is buried deeper in the logic.

流通常是 terser 。同样的例子说明了这一点。 Terser并不总是更好,但是如果你可以同时表达简洁和表达,那就更好了。

Streams are often terser. The same example shows this. Terser isn't always better, but if you can be terse and expressive at the same time, so much the better.

Streams与函数有很强的亲和力即可。 Java 8引入了lambdas和功能接口,它打开了一个强大技术的整个玩具箱。 Streams提供了将函数应用于对象序列的最方便和自然的方式。

Streams have a strong affinity with functions. Java 8 introduces lambdas and functional interfaces, which opens a whole toybox of powerful techniques. Streams provide the most convenient and natural way to apply functions to sequences of objects.

Streams鼓励更少的可变性。这与函数式编程方面有关 - 使用流编写的程序类型往往是那种不修改对象的程序。

Streams encourage less mutability. This is sort of related to the functional programming aspect -- the kind of programs you write using streams tend to be the kind of programs where you don't modify objects.

Streams鼓励更松散的耦合。您的流处理代码不需要知道流的来源或其最终的终止方法。

Streams encourage looser coupling. Your stream-handling code doesn't need to know the source of the stream, or its eventual terminating method.

Streams可以简洁地表达相当复杂的行为。例如:

 stream.filter(myfilter).findFirst();

乍看之下可能会过滤整个流,然后返回第一个元素。但实际上 findFirst()会驱动整个操作,因此在找到一个项目后会有效停止。

Might look at first glance as if it filters the whole stream, then returns the first element. But in fact findFirst() drives the whole operation, so it efficiently stops after finding one item.

Streams为未来的效率提升提供了空间。有些人已经进行了基准测试,发现来自内存 List 或数组的单线程流可能比等效循环慢。这似乎是合理的,因为游戏中有更多的对象和开销。

Streams provide scope for future efficiency gains. Some people have benchmarked and found that single-threaded streams from in-memory Lists or arrays can be slower than the equivalent loop. This is plausible because there are more objects and overheads in play.

但是流规模。除了Java对并行流操作的内置支持外,还有一些用于分布式map-reduce的库使用Streams作为API,因为模型适合。

But streams scale. As well as Java's built-in support for parallel stream operations, there are a few libraries for distributed map-reduce using Streams as the API, because the model fits.

缺点?

效果 循环播放数组在堆和CPU使用方面都非常轻量级。如果原始速度和内存节俭是一个优先事项,使用流更糟糕。

Performance: A for loop through an array is extremely lightweight both in terms of heap and CPU usage. If raw speed and memory thriftiness is a priority, using a stream is worse.

熟悉。这个世界充满了经验丰富的程序程序员,来自许多语言背景,对于他们熟悉的循环和流是新颖的。在某些环境中,您希望编写熟悉此类人员的代码。

Familiarity.The world is full of experienced procedural programmers, from many language backgrounds, for whom loops are familiar and streams are novel. In some environments, you want to write code that's familiar to that kind of person.

认知开销。由于它的声明性质,以及对下面发生的事情的抽象的增加,你可能需要建立一个新的心理模型,用于表示代码与执行的关系。实际上,只有在出现问题时,或者您需要深入分析性能或细微错误时,您才需要这样做。当它正常工作时,它就可以正常工作。

Cognitive overhead. Because of its declarative nature, and increased abstraction from what's happening underneath, you may need to build a new mental model of how code relates to execution. Actually you only need to do this when things go wrong, or if you need to deeply analyse performance or subtle bugs. When it "just works", it just works.

调试器正在改进,但即使是现在,当您逐步完成流代码时一个调试器,它可能比等效循环更难,因为一个简单的循环非常接近传统调试器使用的变量和代码位置。

Debuggers are improving, but even now, when you're stepping through stream code in a debugger, it can be harder work than the equivalent loop, because a simple loop is very close to the variables and code locations that a traditional debugger works with.

这篇关于在Java中,流循环有什么优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆