Reputation: 125
Can I get streams API from this ?
public String getTheMostExpensiveIngredient() {
double help = 0.0;
List<String> result = new ArrayList<>();
for(Map.Entry<Ingredient, Double> x : list.entrySet()) {
if((x.getKey().getPrice() * x.getValue() > help )) {
help = x.getKey().getPrice() * x.getValue();
result.add(x.getKey().getName());
}
}
return result.get(result.size()-1);
}
Upvotes: 0
Views: 767
Reputation: 63955
You are, as far as I can see, just looking for the name of the max element. You don't modify any state. Or you don't have to. With streams you could do
String getTheMostExpensiveIngredient(Map<Ingredient, Double> map) {
return map.entrySet().stream() // Stream<Map.Entry<Ingredient, Double>>
.max(Comparator.comparingDouble(
e -> e.getValue() * e.getKey().getPrice())) // Optional<Map.Entry<..>>
.map(e -> e.getKey().getName()) // Optional<String>
.orElse(null); // just String
}
Stream.max
method to get the max entry.The "tricky" part is to tell the stream api how you define the maximum. It expects a Comparator
for Map entries. This is handled by the Comparator.comparingDouble(value * price function)
. It maps each entry to some value so it can be compared.
Upvotes: 3