---
# System prepended metadata

title: 2353. Design a Food Rating System
tags: [Leetcode, Design, Medium]

---

# 2353. Design a Food Rating System
###### tags: `Leetcode` `Medium` `Design`
Link: https://leetcode.com/problems/design-a-food-rating-system/description/
## 思路
用3个map, food->Rating, food->cuisine, cuisine->food (to get all food of that cuisine, use a TreeSet to keep everything ordered)
之所以我们用TreeSet而不是PriorityQueue是因为排序的key有可能会更新
所以我们需要先删除element 然后再加进去 保证它的key是update过的

注意两点:
1. TreeSet uses the comparator to see if your element exists in the TreeSet (might not be correct, that's from personal experiments). Thus, remove the element, THEN update the rating, THEN insert again. Don't do update, remove, insert. This way, TreeSet will contain duplicates.
changeRating不能写成
```java
foodtoRating.put(food, newRating);
if(!foodtoRating.containsKey(food)) return;
String cuisine = foodtoCuisine.get(food);
cuisinetoRating.get(cuisine).remove(food);
cuisinetoRating.get(cuisine).add(food);
```
2. Always use .equals() to compare Objects. That includes Integer. foodToRat.get(a)==(foodToRat.get(b)) actually would break the code! HashMap.get() returns an Integer.
## Code
```java=
class FoodRatings {
    Map<String, TreeSet<String>> cuisinetoRating = new HashMap<>();
    Map<String, Integer> foodtoRating = new HashMap<>();
    Map<String, String> foodtoCuisine = new HashMap<>();
    public FoodRatings(String[] foods, String[] cuisines, int[] ratings) {
        for(int i=0; i<foods.length; i++){
            foodtoCuisine.put(foods[i], cuisines[i]);
            foodtoRating.put(foods[i], ratings[i]);
            if(!cuisinetoRating.containsKey(cuisines[i])){
                cuisinetoRating.put(cuisines[i], new TreeSet<>((a,b)->(foodtoRating.get(a).equals(foodtoRating.get(b))?a.compareTo(b):foodtoRating.get(b)-foodtoRating.get(a))));
            }
            cuisinetoRating.get(cuisines[i]).add(foods[i]);
        }
    }
    
    public void changeRating(String food, int newRating) {
        if(!foodtoRating.containsKey(food)) return;
        String cuisine = foodtoCuisine.get(food);
        cuisinetoRating.get(cuisine).remove(food);
        foodtoRating.put(food, newRating);
        cuisinetoRating.get(cuisine).add(food);
    }
    
    public String highestRated(String cuisine) {
        if(!cuisinetoRating.containsKey(cuisine)) return "";
        return cuisinetoRating.get(cuisine).first();
    }
}
```