warman
warman

Reputation: 3

how to pass the model class data to hasmap?

My Question is as I put the provided data into ArrayList<>.. using the line cityDataItemList.add(cityDataItem); similarly, how can I put the same data into hashmap object?

public class SampleDataProvider {

    public static List<CityDataItem> cityDataItemList;
    public static Map<String,CityDataItem> dataItemMap;
    static
    {
    cityDataItemList=new ArrayList<>();
    dataItemMap=new HashMap<>();
       addItem(new CityDataItem(null,"Lahore",2,
                "Punjab",15000000,
                "Lahore is 2nd Largest City of Pakistan ",
                "lahore.jpg"));
        addItem(new CityDataItem(null,"Islamabad",3,
                "Capital Terrortory",15000000,
                "Islamabad is a DarulHakumt of Paksitan",
                "islamabad.jpg"));

}

private static void addItem(CityDataItem cityDataItem) {

        cityDataItemList.add(cityDataItem);

    }
}

Upvotes: 0

Views: 46

Answers (1)

iCantC
iCantC

Reputation: 3190

This is what you can do,

dataItemMap.put("your_key",new CityDataItem(null,"Islamabad",3,
            "Capital Terrortory",15000000,
            "Islamabad is a DarulHakumt of Paksitan",
            "islamabad.jpg"));

HashMap provides put() method to insert items according to Key-Value pair, in the above

put("your_key",new CityDataItem(null,"Islamabad",3,
            "Capital Terrortory",15000000,
            "Islamabad is a DarulHakumt of Paksitan",
            "islamabad.jpg"));

your_key is the Key Part and the rest new CityDataItem(null,"Islamabad",3, "Capital Terrortory",15000000, "Islamabad is a DarulHakumt of Paksitan", "islamabad.jpg")); is the Value Part.

You define the type of Key Value when you declare the HashMap variable.For ex the line public static Map<String,CityDataItem> dataItemMap; signifies that variable dataItemMap will consist of two parts,

  1. A Key - which will be a type of String.

  2. A Value - which will be a type of CityDataItem.

You can later extract items from HashMap using the get() method. To extract an already added value, we just need the Key to extract the Value,like this hashMapObj.get("my_key") and you will have the Value which was stored for the provided corresponding Key.

Upvotes: 1

Related Questions