将For-Loop转换为Java流 [英] Convert For-Loop into Java stream

查看:56
本文介绍了将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>

推荐答案

  1. 通过Collection#stream()方法创建SubscriptionsStream
  2. 使用Stream#filter()方法通过过滤掉所有未通过给定谓词的预订来模拟" if语句.
  3. 使用Stream#map()方法将订阅流转换为ID流
  4. 最后,通过使用Stream#collect(),您可以将流收集到所需的任何内容中.例如.一个Set
  1. Create a Stream of Subscriptions via the Collection#stream() method
  2. Use of the Stream#filter() method to "simulate" the if statement, by filtering out all subscription that don't pass the given predicate.
  3. By using the Stream#map() method you convert your stream of subscriptions, to a stream of ids
  4. Finally by using the Stream#collect() you can collect the stream into anything you'd like. E.g. a Set

您的代码可能如下所示:

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(方法参考)在功能上等于lambda sub -> 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 lambda sub -> 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 invoke orders.get(Product) for every element

      这篇关于将For-Loop转换为Java流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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