我是Java 8 Streams的新手,目前正在尝试将for循环转换为Java 8 Streams。我可以帮忙吗?
for (Subscription sub : sellerSubscriptions) {
if (orders.get(Product).test(sub)) {
orderableSubscriptions.add(sub.getId());
}
}
sellerSubscriptions = List.
orders = Map<String,Predicate<Subscription>>
orderableSubscriptions = Set<String>
答案 0 :(得分:2)
Stream
方法创建Subscriptions
的{{1}} Collection#stream()
方法来“模拟” Stream#filter()
语句。 if
方法,将订阅流转换为ID流Stream#map()
,您可以将流收集到所需的任何内容中。例如。一个Stream#collect()
您的代码可能如下所示:
Set
一些注意事项:
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
(方法参考)在功能上等于lambda Subscription::getId
sub -> sub.getId()
(也是方法引用)仅检索一次谓词。由于似乎所有订阅的谓词相同
orders.get(Product)::test
,因为它将为每个元素调用sub -> orders.get(Product).test(sub)