Accessing Hashmap values from another class

I have created 3 HashMaps in a Database class. And I want to check for a certain value in a hashmap before adding an item. So I want to check my Retailer HashMap for a specific value, and if that value exists, I add certain items. I'm not sure how to call the hashmap from another class or how to code that loop, where am I going wrong?

My HashMap creation:

private static Map<Long, User> users = new HashMap<>();
private static Map<Long, Retailer> retailers = new HashMap<>();
private static Map<Long, Item> items = new HashMap<>(); 

My method to create an item/items:

public ItemService(){

    items.put(1l, new Item(1, "Black Suit Shoes", "Black" , "11"));
    items.put(2l, new Item(2, "Nike Runners", "Red" , "7"));
    items.put(3l, new Item(3, "Nike Sports Socks", "Yellow" , "4"));
}

I want to make sure a retailer with a specific Id exists, and if it does, then add these items.

1 answer

  • answered 2017-10-11 10:21 Isac

    To check if a specific key exists in a Map you can use the containsKey method. You didn't make it clear how the Item ids are generated but i will assume that they are unique.

    Considering that you could do the following to add an item:

    public boolean addItemsIfRetailerExists(Long retailerId, Item item){
        if (!retailers.containsKey(retailerId)){
            return false;
        }
    
        items.put(item.id, item);
        return true;
    }
    

    Note that this implies calling the method with the Item you want to insert:

    addItemsIfRetailerExists(5341l, new Item(1, "Black Suit Shoes", "Black" , "11"));
    

    To add more functionality i added a boolean return value which indicates if the item was inserted or not.

    You could even create an overload for this method that would receive an Item array instead to be able to add multiple items at once:

    public boolean addItemsIfRetailerExists(Long retailerId, Item[] itemsToAdd){
        if (!retailers.containsKey(retailerId)){
            return false;
        }
    
        for(Item i:itemsToAdd){
            items.put(i.id, i);
        }
        return true;
    }
    

    Which you can now call with all the items you want to add:

    addItemsIfRetailerExists(5341l, new Item[] { 
        new Item(1, "Black Suit Shoes", "Black" , "11"),
        new Item(2, "Nike Runners", "Red" , "7"),
        new Item(3, "Nike Sports Socks", "Yellow" , "4")});