kalina199
kalina199

Reputation: 222

HashMap getting unintended string for key value

I have this piece of code :

private static void addItem(String[] commandParsed, Set<Item> inventory, Map<String, Map<String, Item>> maps) {
        Item item = new Item(commandParsed[1], Double.parseDouble(commandParsed[2]), commandParsed[3]);
        String mapName = commandParsed[3];
        Map<String, Item> map = new HashMap<>();
        if (inventory.contains(item)) {
            System.out.printf("Error: Item %s already exists%n", item.name);
        } else {
            inventory.add(item);
            System.out.printf("Ok: Item %s added successfully%n", item.name);
             maps.computeIfAbsent(mapName, k -> new HashMap<>()).put(item.name, item);
        }
    }

my Idea is to add all unique items to a set and then to make Map<String, Map<String, Item>> maps where the key is the type of the added item and the value to be map containing all items of that type, but the key to be the Item names. However the keys of the inner maps are again the type of the item. here is some sample input

add CowMilk 1.90 dairy
add BulgarianYogurt 1.90 dairy

I am trying to find out why my inner map key-value pair is not <item.name, Item> but <item.type, Item> since my code is .put(item.name, item);

This is my Item class constructor

 public Item(String name, double price, String type) {
        this.name = name;
        this.price = price;
        this.type = type;
    }

enter image description here

Upvotes: 0

Views: 66

Answers (2)

Joni
Joni

Reputation: 111219

You are misreading the debugger object tree display.

Map entries are key-value pairs.

The "dairy" map entry is a key-value pair with key "dairy", and a value that is another map (with keys "CowMilk" and "BulgarianYogurt")

So it's not that the inner map has a "dairy" key, it's just that expanding the "dairy" map entry exposes "dairy" as the key in the map entry. The keys of the inner map are "CowMilk" and "BulgarianYogurt".

Upvotes: 2

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 78945

I am trying to find out why my inner map key-value pair is not <item.name, Item> but <item.type, Item> since my code is .put(item.name, item);

You need to put {item.name, item} inside the inner map as shown below:

maps.computeIfAbsent(mapName, k -> new HashMap<String, Item>().put(item.name, item));

Upvotes: 1

Related Questions