Reputation:
I have been trying to use Stream instead of the enhanced for loop but I cannot incorporate correctly the if statements. Any help would be much appreciated
List<Donut> newDonuts = new ArrayList<>();
for (Donut currentElement : availableDonuts) {
if (!alreadyPickedDonuts.contains(currentElement)) {
newDonuts.add(currentElement);
if (newDonuts.size() == extraDonutsRequired) {
break;
}
}
}
Upvotes: 1
Views: 140
Reputation: 17289
You can do:
availableDonuts.stream()
.filter(currentElement -> !alreadyPickedDonuts.contains(currentElement))
.limit(extraDonutsRequired)
.collect(Collectors.toList());
Upvotes: 4