将For-Loop转换为Java流 [英] Convert For-Loop into Java stream
本文介绍了将For-Loop转换为Java流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Java 8 Streams的新手,目前正在尝试将for循环转换为Java 8 Streams.我可以帮忙吗?
I'm new to Java 8 Streams and I'm currently trying to convert a for loop into a java 8 stream. Could I get some help?
for (Subscription sub : sellerSubscriptions) {
if (orders.get(Product).test(sub)) {
orderableSubscriptions.add(sub.getId());
}
}
sellerSubscriptions = List.
orders = Map<String,Predicate<Subscription>>
orderableSubscriptions = Set<String>
推荐答案
- 通过
Collection#stream()
方法创建Subscriptions
的Stream
- 使用
Stream#filter()
方法通过过滤掉所有未通过给定谓词的预订来模拟"if
语句. - 使用
Stream#map()
方法将订阅流转换为ID流 - 最后,通过使用
Stream#collect()
,您可以将流收集到所需的任何内容中.例如.一个Set
- Create a
Stream
ofSubscriptions
via theCollection#stream()
method - Use of the
Stream#filter()
method to "simulate" theif
statement, by filtering out all subscription that don't pass the given predicate. - By using the
Stream#map()
method you convert your stream of subscriptions, to a stream of ids - Finally by using the
Stream#collect()
you can collect the stream into anything you'd like. E.g. aSet
您的代码可能如下所示:
Your code could look like this:
Set<String> ids = sellerSubscriptions.stream() // create a Stream<Subscription>
.filter(orders.get(Product)::test) // filter out everthing that doesn't match
.map(Subscription::getId) // only use the ids from now on
.collect(Collectors.toSet()); // create a new Set from the elements
一些注意事项:
-
Subscription::getId
(方法参考)在功能上等于lambdasub -> sub.getId()
-
orders.get(Product)::test
(也是方法引用)仅检索一次谓词.由于您所有订阅的谓词似乎都是相同的- 尽管它不等于
sub -> orders.get(Product).test(sub)
,因为它将为每个元素调用orders.get(Product)
Subscription::getId
(a method reference) is functionally equal to the lambdasub -> sub.getId()
orders.get(Product)::test
(also a method reference) retrieves the predicate only once. As it seems to be the same predicate for all your subscriptions- Though it is not equal to
sub -> orders.get(Product).test(sub)
as that would invokeorders.get(Product)
for every element
这篇关于将For-Loop转换为Java流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Though it is not equal to
- 尽管它不等于
查看全文