user13709439
user13709439

Reputation:

Enhanced for loop to stream

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

Answers (1)

Hadi
Hadi

Reputation: 17289

You can do:

availableDonuts.stream()
            .filter(currentElement -> !alreadyPickedDonuts.contains(currentElement))
            .limit(extraDonutsRequired)
            .collect(Collectors.toList());

Upvotes: 4

Related Questions