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.
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments