0

レストランの ID である整数値としてキーを格納する HashMap を作成したいと考えています。値はレストラン オブジェクトのリストである必要があります。しかし、私の 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));

    }
}

私のレストラン クラスには、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に変換できません)

4

3 に答える 3

3

ll.add(restaurant) はブール値を返します。

だから、あなたがするとき:

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

タイプ (Integer,List) のマップに (int, boolean) を追加しようとしています

また、以下のコードは、すべてのレストランをすべてのシティ ID に追加します。

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);
}
于 2013-10-31T02:56:24.807 に答える
1
  map.put(restaurant.cityId, ll.add(restaurant));

この声明では、

ll.add(restaurant)

return追加操作の値は ですboolean。これが、そのエラーが発生する理由です。

あなたがする必要があるかもしれないことは、次のようなものです:

ll.add(restaurant);
map.put(restaurant.cityId, ll);
于 2013-10-31T02:54:39.687 に答える
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に 1 つずつ追加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);
于 2013-10-31T02:59:52.510 に答える