Home > Software engineering >  Filter Java stream if specific object is a null
Filter Java stream if specific object is a null

Time:06-11

I have the object FastFood. In ArrayList there are 10 hotdogs.

public class FastFood {
    ArrayList<Hotdog> hotdogs;
    boolean isTasty;
}

public class Hotdog {
    String name;
    Ingredients ingredients;
}

For 9 hotdogs all data is filled. For 1 hotdog, the object Ingredients is null.

How can I modify below metod to have only these hotdogs, which have filled Ingredients? (I would like to see 9 hotdogs).

public List<Hotdog> convert(Fastfood fastfood) {
      List<Hotdog> hotdogs = fastfood.getHotdogs().stream()
                    .map(this::convertToHotdog)
                    .collect(Collectors.toList());

CodePudding user response:

If you have list of hotdog objects, you can use filter() method, like this:

List<Hotdog> hotdogs = fastfood.getHotdogs().stream()
                    .filter(hotdog->hotdog.getIngredients()!=null)
                    .collect(Collectors.toList());

NOTE: I'm assuming that you have getter method for ingredients field in Hotdog class which is called getIngredients()

CodePudding user response:

Based on comments & question, it looks like convertToHotdog might be something to do with internal conversion of Hotdog which is not shared as a part of question. In that case, below might be useful:

List<Hotdog> hotdogs = fastfood.getHotdogs().stream()
                    .filter(t->Objects.nonNull(t.getIngredients()))
                    .map(this::convertToHotdog)
                    .collect(Collectors.toList());
  • Related