Convert For-Loop into Java stream

我的梦境 提交于 2021-01-29 07:28:32

问题


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:


  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

Some notes:

  • 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


来源:https://stackoverflow.com/questions/56274366/convert-for-loop-into-java-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!