How to get the data from nested Hashmap? - java

This line of code returns List<HashMap<String, String>>
List<HashMap<String,String>> map= restTemplate.postForObject(url,mvm,List.class);
And through this code, I can succesfully get the value of id and name in index[0].
List<HashMap<String, String>> map;
map.get(0).get("id");
map.get(0).get("name");
The Structure of the map
HashMap<"id","1">
<"name","john">
<"parameters",HashMap<"key", "val"> <"key2","val2">>
How can I get data from parameters? thanks.

To get the value of parameter you could do
String val = ((HashMap)map.get(0).get("parameters")).get("key");
although you will need to change
HashMap<String, String> to HashMap<String, Object> for this to work

((HashMap)map.get(0).get("parameters")).get(map_key)

Try below code:
for(int i=0;i<map.size();i++){
map.get(i).get("id");
map.get(i).get("name");
}
Save each value to your needed variables.

You can only get string values from the Map since it's declared List<HashMap<String,String>>. If it would say List<HashMap<String, Object> you could do something like this:
package com.stackoverflow.maps;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class InnerMaps {
public InnerMaps(List<HashMap<String,Object>> outerList) {
System.out.println("InnerMaps.<init>");
for (HashMap<String, Object> outerMap: outerList) {
for (String key: outerMap.keySet()) {
Object value = outerMap.get(key);
if (value.getClass().getName().equals(HashMap.class.getName())) {
HashMap<String,String> hashMap = (HashMap<String,String>)value;
System.out.println(key + ", hashMap:" + hashMap );
} else {
System.out.println(key + " : " + value);
}
}
}
}
public static void main(String[] args) {
List<HashMap<String,Object>> theList = new ArrayList<>();
HashMap<String,String> innerHashmap = new HashMap<>();
innerHashmap.put("innerOne", "innerOneValue");
innerHashmap.put("innerTwo", "innerTwoValue");
HashMap<String, Object> outer = new HashMap<>();
outer.put("one", new String("One Value"));
outer.put("two", innerHashmap);
theList.add(outer);
InnerMaps app = new InnerMaps(theList);
}
}

Related

Convert nested JsonArray in Map Java

I am trying to write a generic code were a JSON array as below example can be converted to a map .
This is sample .
where parent element is menu
{"menu": {
"items": [
{"id": "Open"},
{"id": "OpenNew", "label": "Open New"},
{"id": "ZoomIn", "label": "Zoom In"},
{"id": "ZoomOut", "label": "Zoom Out"},
{"id": "Quality"},
{"id": "Pause"}
]
}}
to map having map values as :
menu.items_0.id=open
menu.items_1.id=OpenNew
menu.items_1.label=Open New
menu.items_2.id=ZoomIn
menu.items_2.label=Zoom In
menu.items_3.id=ZoomOut
menu.items_3.id=Zoom Out
menu.items_4.id=Quality
menu.items_5.id=Pause
For my answer you need these classes:
org.json.JSONArray;
org.json.JSONException;
org.json.JSONObject;
And I'm assuming a class like this:
public class menu{
private String id;
private String label;
}
To parse - I'm ignoring if it's a stream, file, etc -. However, it assumes you've manipulated your source to create a single long String object called myString.
JSONObject topLevel = new JSONObject( myString );
JSONObject itemsArray= topLevel.getJSONArray("items");
int tempID;
String tempLabel;
//Now go through all items in array.
for(int i =0; i < itemsArray.length(); i++){
tempID = itemsArray.getJSONObject(i).getString("id");
if(itemsArray.getJSONObject(i).has("label"))
tempLabel = itemsArray.getJSONObject(i).getString("label");
else
tempLabel = null;
//whatever action you need to take
menu = new menu( tempId, tempLabel);
}
This code here gets the job done. You can extract some methods, or refactor it a little, but it should do the trick.
public class Example {
public static void main(String[] args) {
String source = "{\"menu\": {\"items\": [{\"id\": \"Open\"},{\"id\": \"OpenNew\", \"label\": \"Open New\"}, " +
"{\"id\": \"ZoomIn\", \"label\": \"Zoom In\"},"
+ "{\"id\": \"ZoomOut\", \"label\": \"Zoom Out\"},{\"id\": \"Quality\"},{\"id\": \"Pause\"}"
+ "]}}";
JSONObject jsonObject = new JSONObject(source);
Map<String, Object> map = jsonObject.toMap();
Map<String, String> resultMap = new HashMap<>();
map
.entrySet()
.forEach(entry -> addToResult(entry, resultMap, "", ""));
System.out.println(resultMap);
}
private static void addToResult(Map.Entry<String, Object> entry, Map<String, String> resultMap, String fieldNameAcummulator, String index) {
Object value = entry.getValue();
if (!Map.class.isAssignableFrom(value.getClass()) && !List.class.isAssignableFrom(value.getClass())) {
resultMap.put(addToAccumulator(entry, fieldNameAcummulator, index), (String) value);
return;
}
if (Map.class.isAssignableFrom(value.getClass())) {
Map<String, Object> nestedMap = (HashMap<String, Object>) value;
nestedMap
.entrySet()
.forEach(nestedEntry -> addToResult(nestedEntry, resultMap, addToAccumulator(entry, fieldNameAcummulator, index), ""));
} else {
List<HashMap<String, Object>> hashMaps = (List<HashMap<String, Object>>) value;
IntStream.range(0, hashMaps.size())
.forEach(listIndex -> {
HashMap<String, Object> nestedMap = hashMaps.get(listIndex);
nestedMap.entrySet().forEach(nestedEntry -> addToResult(nestedEntry, resultMap, addToAccumulator(entry, fieldNameAcummulator, index), String.valueOf(listIndex)));
});
}
}
private static String addToAccumulator(Map.Entry<String, Object> entry, String fieldNameAcummulator, String index) {
return fieldNameAcummulator.isEmpty()
? entry.getKey()
: fieldNameAcummulator + getKeyValueWithIndex(entry, index);
}
private static String getKeyValueWithIndex(Map.Entry<String, Object> entry, String index) {
return index.isEmpty()
? ".".concat(entry.getKey())
: "_".concat(index).concat(".").concat(entry.getKey());
}
}
Feel free to ask if you have any questions regarding the implementation.
Hope it helps!
I have change some logic and it works fine after that.
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonToMapConvertor {
private static HashMap<String, Object> mapReturn = new HashMap<String, Object>();
public static JsonParser parser = new JsonParser();
public static void main(String[] args) throws Exception{
String json ="{\n" +
" \"glossary\": {\n" +
" \"title\": \"example glossary\",\n" +
" \"GlossDiv\": {\n" +
" \"title\": \"S\",\n" +
" \"GlossList\": {\n" +
" \"GlossEntry\": {\n" +
" \"ID\": \"SGML\",\n" +
" \"SortAs\": \"SGML\",\n" +
" \"GlossTerm\": \"Standard Generalized Markup Language\",\n" +
" \"Acronym\": \"SGML\",\n" +
" \"Abbrev\": \"ISO 8879:1986\",\n" +
" \"GlossDef\": {\n" +
" \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n" +
" \"GlossSeeAlso\": [\"GML\", \"XML\"]\n" +
" },\n" +
" \"GlossSee\": \"markup\"\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
HashMap<String, Object> map = createHashMapFromJsonString(json,"");
System.out.println("map size "+map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
if(!entry.getValue().toString().contains("{"))
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
public static HashMap<String, Object> createHashMapFromJsonString(String json,String prefix) throws Exception{
if(json.startsWith("[",0)){
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++){
JSONObject jsonobject = jsonArray.getJSONObject(i);
createHashMapFromJsonString(jsonobject.toString(), prefix+"_"+i);
}
}
else{
JsonObject object = (JsonObject) parser.parse(json);
Set<Map.Entry<String, JsonElement>> set = object.entrySet();
Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
while (iterator.hasNext()) {
Map.Entry<String, JsonElement> entry = iterator.next();
String key = entry.getKey();
if(prefix.length()!=0){
key = prefix + "."+key;
}
JsonElement value = entry.getValue();
if (null != value) {
if (!value.isJsonPrimitive()) {
if (value.isJsonObject()) {
mapReturn.put(key, createHashMapFromJsonString(value.toString(),key));
} else if (value.isJsonArray() && value.toString().contains(":")) {
List<HashMap<String, Object>> list = new ArrayList<>();
JsonArray array = value.getAsJsonArray();
if (null != array) {
for (JsonElement element : array) {
if (!element.isJsonPrimitive()) {
createHashMapFromJsonString(value.toString(),key);
}else{
list.add(createHashMapFromJsonString(value.toString(),key));
}
}
mapReturn.put(key, list);
}
} else if (value.isJsonArray() && !value.toString().contains(":")) {
mapReturn.put(key, value.getAsJsonArray());
}
} else {
mapReturn.put(key, value.getAsString());
}
}
}
}
return mapReturn;
}
}
Just another way of converting JSONObject as List of Map as Generic
public static List<Map<String, Object>> getJsonNode(String jsonContents, String nodeName)
throws JsonProcessingException, IOException, ParseException {
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(jsonContents);
Object o = json.get(nodeName);
List<Map<String, Object>> results = Lists.newArrayList();
if (o instanceof JSONObject) {
results.add((Map<String, Object>) o);
} else if (o instanceof JSONArray) {
List<Map<String, Object>> hashMaps = (List<Map<String, Object>>) o;
results.addAll((Collection<? extends Map<String, Object>>) hashMaps);
}
return results;
}
/**
* Driver
*
* #param args
* #throws IOException
* #throws ParseException
*/
public static void main(String[] args) throws IOException, ParseException {
String jsonInputFile = "temp/input.json";
String jsonContents = new String(Files.readAllBytes(Paths.get(jsonInputFile)));
List<Map<String, Object>> results = getJsonNode(jsonContents, "summary");
for (Map<String, Object> entry : results) {
System.out.println(entry);
}
///////////////////////////////////////
results = getJsonNode(jsonContents, "payWay");
for (Map<String, Object> entry : results) {
System.out.println(entry);
}
///////////////////////////////////////
results = getJsonNode(jsonContents, "sellerDetails");
for (Map<String, Object> entry : results) {
System.out.println(entry);
}
}

Passing a variable from a while loop to another class using org.json.simple json parser

I am trying to get the variables TenderType, TenderAmount, and CrdName so I can send them to another class that will print them out. I do not think I can use getters and setters for this as I am declaring the variable inside the while loop for the org.json.simple parser to work. Still learning :/ Any help would be greatly appreciated!
Here is JSON:
{
"Tender" :
[
{
"TenderType" : "1",
"TenderAmount" : "21.00",
"CrdName" : "Visa"
}
]
}
//So for example the other class will be test() so
(FIRST CLASS)
public class test{
public String callvars(){
JSONtoVar meh = new JSONtoVar();
// ??? not sure the correct way to call any variable over???
return "";
}
}
(SECOND CLASS)
//???Not sure what to do to return variables that are already declared inside of while Parser???
package json;
import java.io.FileReader;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JSONtoVar {
public int PARSEJson(){
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("C:\\Users\\interMind\\Desktop\\variables_json.txt"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray Tender = (JSONArray) jsonObject.get("Tender");
#SuppressWarnings("rawtypes")
Iterator z = Tender.iterator();
while (z.hasNext()) {
JSONObject innerObj = (JSONObject) z.next();
//Trying to get these three strings Below
String TenderType = (String)innerObj.get("TenderType");
String TenderAmount = (String)innerObj.get("TenderAmount");
String CrdName = (String)innerObj.get("CrdName");
System.out.println("\nTender: \n" + TenderType + "\n" + TenderAmount + "\n" + CrdName);
}
}
catch (Exception e) {
e.printStackTrace();
}
return 1;
}
} //ends class
In the method parseJson in class JSONtoVar, do following
a. Change return type of parseJson to Map
public Map<String,String> parseJson(){..... }
b. Create a Hashmap
HashMap<String, String> tender= new HashMap<String, String>();
c. Add TenderType, TenderAmount and CrdNo in the HashMap.
tender.put("TenderType",TenderType);
tender.put("TenderAmount",TenderAmount);
tender.put("CrdName",CrdName);
d. Return HashMap to caller, return tender
In the calling method (test.callvars )create an instance of caller class and retrieve value from hashmap
JSONtoVar jsonToVar=new JSONtoVar();
HashMap<String, String> mapJson=(HashMap<String, String>)jsonToVar.parseJson();
System.out.println("mapJson TenderType "+mapJson.get("TenderType"));
System.out.println("mapJson TenderAmount "+mapJson.get("TenderAmount"));
System.out.println("mapJson CrdName "+mapJson.get("CrdName"));
 
Sample code
public class myMain {
public static void main(String[] args) {
JSONtoVar jsonToVar=new JSONtoVar();
HashMap<String, String> mapJson=(HashMap<String, String>) jsonToVar.parseJson();
System.out.println("mapJson TenderType "+mapJson.get("TenderType"));
System.out.println("mapJson TenderAmount "+mapJson.get("TenderAmount"));
System.out.println("mapJson CrdName "+mapJson.get("CrdName"));
}
}
class JSONtoVar {
public Map<String,String> parseJson(){
HashMap<String, String> tender= new HashMap<String, String>();
/*
Get the value from JSON and set value.This has already be done by you
*/
tender.put("TenderType",TenderType) ;
tender.put("TenderAmount",TenderAmount);
tender.put("CrdName",CrdName);
return tender;
}
}

How to copy value from one list to another list having different objects

I have MaterailInfo and StyleInfo, I want to set styleDescription based on StyleNumber matching with materialNumber. I am using 2 for loops, is there any alternative solution?
MaterailInfo:
class MaterailInfo {
private String materialNumber;
private String materialDescription;
public MaterailInfo(String materialNumber, String materialDescription) {
this.materialNumber = materialNumber;
this.materialDescription = materialDescription;
}
// getter setter methods
}
StyleInfo:
class StyleInfo {
private String StyleNumber;
private String styleDescription;
public StyleInfo(String styleNumber, String styleDescription) {
StyleNumber = styleNumber;
this.styleDescription = styleDescription;
}
// getter setter toString methods
}
TEst12:
public class TEst12 {
public static void main(String[] args) {
List<MaterailInfo> mList = new ArrayList<MaterailInfo>();
mList.add(new MaterailInfo("a", "a-desc"));
mList.add(new MaterailInfo("b", "b-desc"));
mList.add(new MaterailInfo("c", "c-desc"));
List<StyleInfo> sList = new ArrayList<StyleInfo>();
sList.add(new StyleInfo("a", ""));
sList.add(new StyleInfo("b", ""));
sList.add(new StyleInfo("c", ""));
for (MaterailInfo m : mList) {
for (StyleInfo s : sList) {
if (s.getStyleNumber().equals(m.getMaterialNumber())) {
s.setStyleDescription(m.getMaterialDescription());
}
}
}
System.out.println(sList);
}
}
If you use a Map instead of a List to store your data, you can get away with doing only a single loop:
Map<String, String> mMap = new HashMap<String, String>();
mMap.put("a", "a-desc");
mMap.put("b", "b-desc");
mMap.put("c", "c-desc");
Map<String, String> sMap = new HashMap<String, String>();
sMap.put("a", "");
sMap.put("b", "");
sMap.put("c", "");
for (Map.Entry<String, String> entry : mMap.entrySet()) {
sMap.put(entry.getKey(), mMap.get(entry.getKey());
}
This code will leave the style description empty if the style number does not match any known material number.
If your numbers can't have duplicates, using a HashMap instead of classes can be a bit faster.
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Demo {
public static void main(String[] args) {
HashMap<String, String> mList = new HashMap();
HashMap<String, String> sList = new HashMap();
mList.put("a", "a-desc");
mList.put("b", "b-desc");
mList.put("c", "c-desc");
sList.put("a", "");
sList.put("b", "");
sList.put("c", "");
Iterator entries = sList.entrySet().iterator();
while (entries.hasNext()) {
Entry entry = (Entry) entries.next();
if (mList.containsKey(entry.getKey())) {
sList.put((String) entry.getKey(), mList.get(entry.getKey()));
}
}
for (Map.Entry<String, String> entry : sList.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
You can do this using one for loop like this
for (int i = 0; i < mList.size(); i++) {
sList.get(i).setStyleDescription(mList.get(i).getMaterialDescription());
}
Note: i am assuming you have balanced lists in term of size.

Using multiple HashMaps to retrieve values in Java

Consider two HashMaps. The first one contains the product name and product category code as key and value respectively. The second HashMap contains the product name and the units sold. I need to write a Java function which accepts the two hash maps and return the names of products in each category which is having the highest number of units sold.
Input1 :{“lux”:”soap”,”colgate”:”paste”, ”pears”:”soap”,”sony”:”electronics”,”samsung”:”electronics”}
Input 2:{“lux”:1000,”colgate”:500,”pears”:2000,”sony”:100,” samsung”,600}
Output: {“pears”,”colgate”,”samsung”}
#Arjun: answer code is given below :
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MultipleHashMapAccessDemo {
protected Map<String, String> getProductCategoryMap() {
Map<String, String> productCategoryMap = new HashMap<String, String>();
productCategoryMap.put("Lux", "Soap");
productCategoryMap.put("Pears", "Soap");
productCategoryMap.put("Dove", "Soap");
productCategoryMap.put("Colgate", "Paste");
productCategoryMap.put("Babul", "Paste");
productCategoryMap.put("Vico", "Paste");
return productCategoryMap;
}
protected Map<String, Integer> getProductUnitsSoldMap() {
Map<String, Integer> productUnitsSoldMap = new HashMap<String, Integer>();
productUnitsSoldMap.put("Lux", 1000);
productUnitsSoldMap.put("Pears", 3000);
productUnitsSoldMap.put("Dove", 3010);
productUnitsSoldMap.put("Colgate", 50);
productUnitsSoldMap.put("Babul", 45);
productUnitsSoldMap.put("Vico", 80);
return productUnitsSoldMap;
}
protected Map<String, String> getExpectedProductCategoryMap(
Map<String, String> productCategoryMap,
Map<String, Integer> productUnitsSoldMap) {
Map<String, String> expectedProductCategoryMap = new HashMap<String, String>();
Set<String> categortSet = new HashSet<String>();
Iterator iterator = productCategoryMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> mEntry = (Map.Entry) iterator.next();
categortSet.add(mEntry.getValue());
}
for (String category : categortSet) {
int tempUnits = 0;
String desiredProductName = null;
for (Object object : productUnitsSoldMap.entrySet()) {
Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) object;
String product = entry.getKey();
if (category.equals(productCategoryMap.get(product))) {
if (tempUnits < entry.getValue()) {
tempUnits = entry.getValue();
desiredProductName = product;
}
}
}
expectedProductCategoryMap.put(category, desiredProductName);
}
return expectedProductCategoryMap;
}
public static void main(String... strings) {
MultipleHashMapAccessDemo accessDemo = new MultipleHashMapAccessDemo();
Map<String, String> productCategoryMap = accessDemo
.getProductCategoryMap();
Map<String, Integer> productUnitsSoldMap = accessDemo
.getProductUnitsSoldMap();
Map<String, String> expectedProductCategoryMap = accessDemo
.getExpectedProductCategoryMap(productCategoryMap,
productUnitsSoldMap);
for (Object object : expectedProductCategoryMap.entrySet()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) object;
System.out.print("Category name is : " + entry.getValue());
System.out.println(" And Product name is : " + entry.getKey());
}
}
}
Basically, I'll hold a map with from the category to the most popular item and its counter. You can either do this with two separate Maps, jimmy up a quick and dirty class to hold the info, or use something like Apache Commons Lang's Pair class. Without relying on any third party, I'd just define a simple class like this:
public class Item {
String name;
int amount;
// constructor from name, amount
// getters and setters
}
Now, you can iterate over the sales map and just save the most popular item for each category:
public Set<String> getPopularItems
(Map<String, String> itemCategories,
Map<String, Integer> itemSales) {
Map<String, Item> result = new HashMap<String, Item();
for (Map.Entry<String, Integer> salesEntry: itemSales) {
String itemName = itemSales.getKey();
int itemAmount = itemSales.getValue();
String category = itemCategories.get(itemName);
if (result.contiansKey(category)) {
int currAmount = result.get(category).getAmount();
if (itemAmount > currAmount) {
result.put (category, new Item (itemName, itemAmount));
}
} else {
result.put (category, new Item (itemName, itemAmount));
}
}
return result.keySet();
}
Note that this is a simplified implementation that does not deal with malformed inputs (e.g., a category that appears in one map but not the other), or with edge cases (e.g., two items with the same amount of sales). This is done for clarity's sake - I'm sure you could add these on later if needed.

Retriving the values of Map inside List

ArrayList<HashMap<String, Object>> list = ArrayList<HashMap<String, Object>>()
I have an array list which contains an hashmap, i am able to get the position of my List , now how would i get the key and value of the object in my List.
#Override
public View getDropDownView() {
System.out.println(data.get(position)); // i am getting my List Objects
}
// The below is the output of data.get(position)
{"title":"hello"}, => 0
{"title":"hello1"}, => 1
{"title":"hello2"}, => 2
{"title":"hello3"}, => 3
Try this out :
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
for (Map element : list) {
Set<Map.Entry<String, Object>> entrySet = element.entrySet();
for (Map.Entry<String, Object> mapEntry : entrySet) {
System.out.println("Key is : " + mapEntry.getKey());
System.out.println("Value is : " + mapEntry.getValue());
}
}
Little modification in above code.Please find the below code snippets.
public class Test01 {
public static void main(String[] args) {
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map=new HashMap<String, Object>();
map.put("test_key", "test_value");
data.add(map);
HashMap hashMap = data.get(0);
Iterator<Object> iterator=hashMap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, Object> entry=(Entry<String, Object>) iterator.next();
System.out.println("Key :"+entry.getKey()+" Value : "+entry.getValue());
}
}
}
i hope this may be help...
With full example try this:
ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> map1 = new HashMap<String, Object>();
HashMap<String, Object> map2 = new HashMap<String, Object>();
map1.put("title", "hello");
map2.put("title2", "hello2");
list.add(map2);
list.add(map1);
HashMap<String, Object> innerMap;
for(int i=0;i<list.size();i++)
{
innerMap = list.get(i);
for (Map.Entry<String, Object> entry : innerMap.entrySet())
{
System.out.println(entry.getKey() + "/" + entry.getValue());
}
}
Your question leaves much to be desired, but I believe this is what you're looking for
public class HashMapClass {
public static void main(String[] args){
ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
//Get the Hasmap at position
HashMap map = data.get(position);
//Get the data in a the hashmap
Object obj = map.get(key);
}
}
You could use Map.Entry
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Y {
public static void main(String[] args) {
// Your data structure...
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
//Add some dummy data
Map<String, Object> map = new HashMap<String, Object>();
map.put("1", "A");
map.put("2", "B");
map.put("3", "C");
//Add the Map to the List
list.add(map);
int positionInList = 0; //Manipulate this how you want
//Use Map.Entry to access both key and value
for (Entry<String, Object> entry : list.get(positionInList).entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
}
}
}

Categories