Creating Map Variable and Map List

Create a Map variable

// Create a new HashMap
HashMap<String, Object> mapVariable = new HashMap<String, Object>();
// Add items to the HashMap
mapVariable.put("name", "Suresh Raina");
mapVariable.put("age", "29");
mapVariable.put("country", "India");

Get data from a Map variable and display in TextViews

// .get(key)
textview1.setText(mapVariable.get("name").toString());
textview2.setText(mapVariable.get("age").toString());
textview3.setText(mapVariable.get("country").toString());
		

Create a Map List

// Create a new Array of type HashMap
ArrayList<HashMap<String, Object>> maplist = new ArrayList<>();
// Create and add HashMap to the ArrayList
{
HashMap<String, Object> _item = new HashMap<>();
_item.put("name", "Rohit Sharma");
_item.put("age", "31");
_item.put("birthplace", "Nagpur");
maplist.add(_item);
}
{
HashMap<String, Object> _item = new HashMap<>();
_item.put("name", "Virat Kohli");
_item.put("age", "30");
_item.put("birthplace", "Delhi");
maplist.add(_item);
}
{
HashMap<String, Object> _item = new HashMap<>();
_item.put("name", "M S Dhoni");
_item.put("age", "37");
_item.put("birthplace", "Ranchi");
maplist.add(_item);
}
{
HashMap<String, Object> _item = new HashMap<>();
_item.put("name", "Ravindra Jadeja");
_item.put("age", "30");
_item.put("birthplace", "Jamnagar");
maplist.add(_item);
}
{
HashMap<String, Object> _item = new HashMap<>();
_item.put("name", "Shikhar Dhawan");
_item.put("age", "33");
_item.put("birthplace", "Delhi");
maplist.add(_item);
}

Get data from position 2 of Map list and display in TextViews

// .get(position).get(key)
textview1.setText(maplist.get((int)2).get("name").toString());
textview2.setText(maplist.get((int)2).get("age").toString());
textview3.setText(maplist.get((int)2).get("birthplace").toString());
		

Leave a Reply