问题
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:
- Create a
StreamofSubscriptionsvia theCollection#stream()method - Use of the
Stream#filter()method to "simulate" theifstatement, 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
Some notes:
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
- Though it is not equal to
来源:https://stackoverflow.com/questions/56274366/convert-for-loop-into-java-stream