Micky
Micky

Reputation: 125

The assignment in streams (java)

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

Answers (1)

zapl
zapl

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
}
  • First this turns the map you have into a stream of it's entries.
  • Then it uses the Stream.max method to get the max entry.
  • And finally it extracts the name from the entry and turns it into a raw String.

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

Related Questions