HashMap 中对象的数组列表形式的值

noo*_*der 0 java list arraylist hashmap

我想创建一个 HashMap,将键存储为整数值,即餐厅的 ID。该值应该是 Restaurant 对象的列表。但我的 IDE 对将餐厅对象添加到列表时的方式不满意。这是我的代码:

public List getTopPerformers(List<RestaurantInfo> restaurants){

    HashMap <Integer, List<RestaurantInfo>> map = new HashMap<Integer,
                                             List< RestaurantInfo>>();
             // Key is restaurant ID. Value is the Object of Class RestaurantInfo
    List<RestaurantInfo> ll;
    for(RestaurantInfo restaurant: restaurants){

        map.put(restaurant.cityId, ll.add(restaurant));

    }
}
Run Code Online (Sandbox Code Playgroud)

我的 Restaurant 类具有 cityId、orderCount 和restaurantId 属性。

map.put(restaurant.cityId, ll.add(restaurant));行给出如下错误,显然它永远不会编译。

no suitable method found for put(int,boolean)
method HashMap.put(Integer,List<RestaurantInfo>) is not applicable
Run Code Online (Sandbox Code Playgroud)

(实参boolean无法通过方法调用转换转换为List)

Aks*_*hay 5

ll.add(restaurant) 返回布尔值。

所以,当你这样做时:

map.put(restaurant.cityId, ll.add(restaurant));
Run Code Online (Sandbox Code Playgroud)

您正在尝试将 (int, boolean) 添加到类型的映射: (Integer,List)

另外,下面的代码会将所有餐厅添加到每个 cityid:

List<RestaurantInfo> ll = new List<RestaurantInfo>();
for(RestaurantInfo restaurant: restaurants){
    ll.add(restaurant);
    map.put(restaurant.cityId, ll);
}
Run Code Online (Sandbox Code Playgroud)

我认为你需要的是:

List<RestaurantInfo> ll;
for (RestaurantInfo restaurant: restaurants) {
  // If restaurant is from the same city which is present in the map then add restaurant to the existing list, else create new list and add.
  if (map.containsKey(restaurant.cityId)) {
    ll = map.get(restaurant.cityId);
  } else {
    ll = new List<RestaurantInfo>();
  }
  ll.add(restaurant);
  map.put(restaurant.cityId, ll);
}
Run Code Online (Sandbox Code Playgroud)