0

How can I get items by conditions? for example:

public class Candy {
    int SugarCantains = 0;
    Candy(int sugarcontains){
        this.SugarCantains = sugarcontains;
    }
    static List<Candy> candies = new ArrayList<>();

    {
        for (int I = 0; I < 9; I++){
            candies.add(new Candy(I))
        }
    }
}

And how can I get candies that SugarContains is less that 5 in list candies?

candies.getByConditions((SugarContains < 5));

I know I can use for loop:

List<Candy> LowSugarCandies = new ArrayList<>();
for (Candy c: candies){
    if (c.SugarContains < 5){
        LowSugarCandies.add(c);
    }
}

but it's too slow, are there any faster way to do that?

And I have same problem in python, how can I do that in python?

Cflowe Visit
  • 331
  • 1
  • 4
  • 12
  • @Chris not at all, I also have same problem at python – Cflowe Visit Mar 31 '22 at 00:17
  • Sure it does: `List lowSugarCandies = candies.stream().filter(c -> c.SugarContains < 5).collect(Collectors.toList());` – shmosel Mar 31 '22 at 00:19
  • 1
    Python would look similar. Something like: `low_sugar_candies = list(filter(lambda c: c.sugar_contains < 5, candies))` or using a list comprehension: `low_sugar_candies = [c for c in candies if c.sugar_contains < 5]`. – Chris Mar 31 '22 at 00:22
  • If you really want to be clever: `low_sugar_candies = list(filter((5).__ge__, candies))` – Chris Mar 31 '22 at 00:26

0 Answers0