值作为HashMap中对象的arraylist

时间:2013-10-31 02:51:49

标签: java list arraylist hashmap

我想创建一个HashMap,它将key存储为Integer值,即餐馆的ID。该值应为Restaurant对象的List。但是我的IDE对于将菜单对象添加到List时的方式并不满意。这是我的代码:

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));

    }
}

我的餐厅类的属性为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

(实际参数boolean不能通过方法调用转换转换为List)

3 个答案:

答案 0 :(得分:3)

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

所以,当你这样做时:

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

你试图将(int,boolean)添加到类型为的地图:(整数,列表)

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

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

我认为你需要的是:

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);
}

答案 1 :(得分:1)

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

在本声明中,

ll.add(restaurant)
添加操作的

return值为boolean,这就是您收到该错误的原因。

您可能需要做的事情如下:

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

答案 2 :(得分:1)

集合

add(E)函数返回布尔值:true如果添加了数据E并且集合结构已被添加已更改(如果此集合不允许重复并且已包含指定的元素,则返回false)。

因此:

for(RestaurantInfo restaurant: restaurants){
        map.put(restaurant.cityId, ll.add(restaurant));
    }

基本上相当于:

for(RestaurantInfo restaurant: restaurants){
            map.put(restaurant.cityId, boolean);
        }

因此,首先将resutaurant个实例逐一添加到列表ll,然后将ll列表实例添加到map

您可能希望执行以下操作:

RestaurantInfo restaurant =  resturants.get(0);
int cityId = restaurant.cityId;

List<RestaurantInfo> ll = new ArrayList<>();

for(RestaurantInfo restaurant: restaurants){
            ll.add(restaurant);
        }

 map.put(cityId, ll);
相关问题