Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java streams list of objects

I have troubles using java streams. I have two classes: Pizza class

public class Pizza {
    private final String name;
    private final List<Ingredient> ingredients;
    // ...
}

and Ingredient class with those :

private final String preetyName;
private final int price;
private final boolean meat;
private final boolean spicy;

I need to use streams but I'm pretty new to this. First I need to make formatted menu: I have List<Pizza> and after using streams it should return something like this

pizza_name: ingredient1_preetyname, ingredient2_preetyname...\npizza2_name...

as one string. I have something like this but It just a string of all ingredients. I dont know how to add pizza name and \n after ingredients

String lista=pizzas.stream()
                    .flatMap(p -> p.getIngredients().stream())
                    .map(i ->i.getPreetyName())
                    .collect(Collectors.joining(", "));

2.Second thing is I need to return the cheapest spicy(at least one ingredient is spicy) pizza. I know I have to fiter pizzas for spicy ingredients and I know i have to sum ingredients prices but i have honestly no idea how to do that.

If someone could help my in any possible way, I will be thankful.

like image 851
Molioo Avatar asked Jan 29 '26 02:01

Molioo


1 Answers

You can obtain the String you want with the following:

String str =
    pizzas.stream()
          .map(p -> p.getName() + ": " + 
                     p.getIngredients().stream()
                                       .map(Ingredient::getPreetyName)
                                       .collect(Collectors.joining(", "))
          )
          .collect(Collectors.joining(System.lineSeparator()));

This creates a Stream<Pizza> of all the pizzas. For one pizza, we need to map it to the corresponding String representation, which is its name, followed by all of the pretty names of the ingredients joined with a comma.

Finally when we have all those Strings for all pizzas, we can join it again, this time separated with the line separator.


As for your second question about retrieving the cheapest pizza, I will assume that the price of a pizza is the sum of the price of all its ingredients. In this case, you can filter all pizzas by keeping only the spicy ones (this is obtained by seeing if any ingredients is spicy) and returning the minimum for the comparator comparing the sum of the price of the ingredients of the pizza.

Pizza cheapestSpicy =
    pizzas.stream()
          .filter(p -> p.getIngredients().stream().anyMatch(Ingredient::isSpicy))
          .min(Comparator.comparingInt(
             p -> p.getIngredients().stream().mapToInt(Ingredient::getPrice).sum()
          )).orElse(null);
like image 87
Tunaki Avatar answered Jan 30 '26 15:01

Tunaki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!