0

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());
1
  • To remove objects with null property you need to apply filter(), or if you don't need them at all you can use fastfood.getHotdogs().removeIf(hd -> hd.getIngredients() == null); instead of creating a stream. What does the method convertToHotdog is meant to do? getHotdogs() returns a list of Hotdogs and result is also List<Hotdog>, so what is happening in between? Commented Jun 10, 2022 at 14:07

2 Answers 2

2

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Minor, but Objects.nonNull exists mainly to be used as a method lambda; != null would be more idiomatic. .filter(t->t.getIngredients() != null)
2

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()

6 Comments

is there any way to do it before .map() method?
I don't understand why do you need this method convertToHotdog? You already have list of hotdogs. This fastfood.getHotdogs().stream() will give you stream of hotdog objects.
it's received from external service in a crazy way and need advanced mapping :D this is why I'm trying to do this before .map() if this is possible
But this fastfood.getHotdogs() will give you list of hotdogs, rights?
yes but I'm getting nullpointer in .map()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.