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.
Related
There is a hashmap and below is the requirement :
Map<String, Object> objectmetainfo = new HashMap();
objectmetainfo.put("userdetails.info.metadata.user.home.address.details", "address");
objectmetainfo.put("userdetails.info.metadata.user.id", "id");
objectmetainfo.put("userdetails.info.metadata.userSupervisor.id", "id");
objectmetainfo.put("info.metadata.code", "code");
objectmetainfo.put("zip", "zip");
Get all the records of hashmap and iterate it
Split the Key based on delimiter and convert it to Pair or Hashmap
The number of delimiter will vary in each string
Below should be the output :
E.g.: For "userdetails.info.metadata.user.home.address.details", "address", below output is required
HashMap<userdetails, HashMap<info, HashMap<metadata, HashMap<user, HashMap<home, HashMap<address, Map<details, address>>>>>>>
or Pair<String, Object> pair = new Pair("userdetails", new Pair("info", new Pair("metadata", new Pair("user", new Pair("home", new Pair("address", new Pair("details", "addressvalue")))))));
Assuming your string won't be crazy long this would work, otherwise you'd get a StackOverflow error.l
I did this using a recursive approach
Split keys by "."
Convert them to the list iterator
Iterate this list recursively to create a nested map
At the end of recursion put the value from objectmetainfo map.
Create an empty result map and recursively merge all the results.
Code:
import java.util.*;
public Map<String, Object> nestedMaps(Iterator<String> keys, String value) {
if (keys.hasNext()) {
String key = keys.next();
Map<String, Object> nestMap = nestedMaps(keys, value);
Map<String, Object> map = new HashMap<>();
map.put(key, nestMap);
if (Objects.equals(nestMap, null))
map.put(key, value);
return map;
}
return null;
}
public void mergeNested(Object srcObj, Object targetObj) {
if (srcObj instanceof Map && targetObj instanceof Map) {
Map<String, Object> srcMap = (Map<String, Object>) srcObj;
Map<String, Object> targetMap = (Map<String, Object>) targetObj;
for (String targetKey : targetMap.keySet()) {
if (srcMap.containsKey(targetKey)) {
mergeNested(srcMap.get(targetKey), targetMap.get(targetKey));
} else {
srcMap.putAll(targetMap);
}
}
}
}
public Map<String, Object> objectmetainfo = new LinkedHashMap<>();
objectmetainfo.put("userdetails.info.metadata.user.home.address.details", "addressValue");
objectmetainfo.put("userdetails.info.metadata.user.id", "id");
objectmetainfo.put("userdetails.info.metadata.userSupervisor.id", "id");
objectmetainfo.put("info.metadata.code", "code");
objectmetainfo.put("zip", "zip");
public Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, Object> e : objectmetainfo.entrySet()) {
List<String> keys = new ArrayList<>(Arrays.asList(e.getKey().split("\\.")));
Map<String, Object> nestedMaps = nestedMaps(keys.iterator(), String.valueOf(e.getValue()));
mergeNested(result, nestedMaps);
}
System.out.println(result);
I printed out all the hashmaps using toString method.
Output:
{
zip= zip,
userdetails= {
info= {
metadata= {
userSupervisor= {
id= id
},
user= {
id= id,
home= {
address= {
details= addressValue
}
}
}
}
}
},
info= {
metadata= {
code= code
}
}
}
Below is the modified logic to remove 2nd recursive call, with this method we are passing the objMap as reference and finally we will have the objMap ready with result
Map<String, Object> objMap = new HashMap<>();
for (Map.Entry<String, Object> e : getObjectMetaInfoMap().entrySet()) {
populateMetaDataMap(keys.iterator(), String.valueOf(e.getValue()), objMap, true, StringUtils.EMPTY);
}
public static Map<String, Object> populateMetaDataMap(Iterator<String> keys, String value, Map<String, Object> objMap, boolean newCall, String matchingKey) {
if (keys.hasNext()) {
String key = keys.next();
if(objMap.get(key) != null && objMap.get(key) instanceof Map) {
return populateMetaDataMap(keys, value, (Map<String, Object>) objMap.get(key), newCall, matchingKey );
} else {
if(newCall) {
newCall = false;
matchingKey = key;
}
Map<String, Object> nestMap = populateMetaDataMap(keys, value, objMap, newCall, matchingKey);
Map<String, Object> map = new HashMap<>();
if (Objects.equals(nestMap, null))
map.put(key, value);
else
map.put(key, nestMap);
if(key.equals(matchingKey)) {
if(Objects.equals(nestMap, null)) {
objMap.put(key, value);
} else {
objMap.put(key, nestMap);
}
}
return map;
}
}
return null;
}
I have three HashMap of this generic type HashMap<String,Server> but I want to combine the data of all the HashMap based on my unique key. But only Server pojo has different data.
So first hashmap has some servers information like ip_address and server name therefore I have both values in map and ip_address as key. Then I have some other hardware spec stored in other map and ip_address as key and so same in third map.
Therefore, combining all POJO based on key I will get complete server information with corresponding ip_address.
I don't know how to do it without doing nested operation
Here is a way to do this. I have shown the example code using only two Map collections, and, the third can be applied in similar way.
I am using Map's computeIfPresent method to "merge" the values of the two maps. The BiFunction (the argument for the computeIfPresent) need to take care of the "merging" aspect - any validations, etc., presently not known (to me). Also, see the note below on computeIfPresent.
Example code:
import java.util.*;
import java.util.function.*;
public class CombiningMaps {
private static Map<String, ServerInfo> map1 = new HashMap<>();
private static Map<String, ServerInfo> map2 = new HashMap<>();
private static BiFunction<String, ServerInfo, ServerInfo> combineWithMap2 =
(k, v) -> {
if (map2.get(k) != null) {
ServerInfo v2 = map2.get(k);
// combine values of map1 and map2
v.setHw2(v2.getHw2());
}
return v;
};
public static void main(String [] args) {
// Add some test data to map 1
map1.put("serv1", new ServerInfo("0A", "a1", "",""));
map1.put("serv2", new ServerInfo("0B", "b1", "",""));
map1.put("serv3", new ServerInfo("0C", "c1", "",""));
System.out.println(map1);
// Add some data to map 2
map2.put("serv1", new ServerInfo("0A", "", "a2",""));
map2.put("serv2", new ServerInfo("0B", "", "b2",""));
map2.put("serv3", new ServerInfo("0C", "", "c2",""));
System.out.println(map2);
// Update map1 with map 2's info
map1.forEach((k,v) -> map1.computeIfPresent(k, combineWithMap2));
System.out.println(map1);
}
}
class ServerInfo {
private String ipAddr;
private String hw1; // hw stands for hardware related info
private String hw2;
private String hw3;
public ServerInfo(String ipAddr, String hw1, String hw2, String hw3) {
this.ipAddr = ipAddr;
this.hw1 = hw1;
this.hw2 = hw2;
this.hw3 = hw3;
}
public String getIpAddr() {
return ipAddr;
}
public String getHw1() {
return hw1;
}
public void setHw1(String s) {
hw1 = s;
}
public String getHw2() {
return hw2;
}
public void setHw2(String s) {
hw2 = s;
}
public String getHw3() {
return hw3;
}
public void setHw3(String s) {
hw3 = s;
}
public String toString() {
return ipAddr + ":" + hw1 + "-" + hw2 + "-" + hw3;
}
}
The output:
{serv2=0B:b1--, serv3=0C:c1--, serv1=0A:a1--}
{serv2=0B:-b2-, serv3=0C:-c2-, serv1=0A:-a2-}
{serv2=0B:b1-b2-, serv3=0C:c1-c2-, serv1=0A:a1-a2-}
How the computeIfPresent behaves (some scenarios):
Consider a Map<String, Integer> map with keys and values: {four=4, one=1, ten=10, two=2, three=3, five=5, eleven=11, twelve=null}
(1) updates the mapping with new value (note the lambda is a BiFunction returning a newly computed value):
map.computeIfPresent("ten", (k, v) -> new Integer(100));
(2) the function returns a null, the existing mapping is removed:
map.computeIfPresent("eleven", (k, v) -> null);
(3) the mapping is not added, as there is no existing mapping:
map.computeIfPresent("twenty", (k, v) -> new Integer(20));
(4) the existing value is null, so there is no change:
map.computeIfPresent("twelve", (k, v) -> new Integer(12));
After getting all values in three maps I used finalMap to combine values. Here is the working for it since the key is same in all map therefore getting key of map using key of
map1 was a good idea.
Set<Map.Entry<String, Server>> set1 = map.entrySet();
for (Map.Entry<String, Server> me : set1) {
Server server=new Server();
server.setIp_Address(me.getKey());
server.setServerName(me.getValue().getServerName());
server.setOsName(map1.get(me.getKey()).getOsName());
server.setOsVersion(map1.get(me.getKey()).getOsVersion());
server.setOsArchitecture(map1.get(me.getKey()).getOsArchitecture());
server.setHardDiskCapacity(map1.get(me.getKey()).getHardDiskCapacity());
server.setRamCapacity(map1.get(me.getKey()).getRamCapacity());
server.setAvgNetWorkUtilizationSent(map2.get(me.getKey()).getAvgNetWorkUtilizationSent());
server.setAvgNetworkUtilizationReceived(map2.get(me.getKey()).getAvgNetworkUtilizationReceived());
server.setAvgCPUtilization(map2.get(me.getKey()).getAvgCPUtilization());
server.setAvgRamUtilization(map2.get(me.getKey()).getAvgRamUtilization());
finalMap.put(me.getKey(), server);
}
Set<Map.Entry<String, Server>> set2 = finalMap.entrySet();
for (Map.Entry<String, Server> me : set2) {
System.out.println(" ServerIP : "+ me.getValue().getIp_Address()+"\t"+" Server Name :"+me.getValue().getServerName()+"\t \t"+" Hardware Capacity :"+me.getValue().getHardDiskCapacity()+"\t"+" Average CPU Utlization: "+me.getValue().getAvgCPUtilization());
}
Use putAll():
Map<String, Server> all = new HashMap<>();
all.putAll(map1);
all.putAll(map2);
all.putAll(map3);
If you want a one-liner:
Map<String, Server> all = Stream.of(map1, map2, map3)
.reduce(new HashMap<>(), (a, b) -> {a.putAll(b); return a;});
Collisions result in replacement.
Your problem it to merge two POJO classes.
For example
class Server {
private String ipAddr;
private String hw1;
private String hw2;
private String hw3;
//Getter and Setters
}
Server s1 = new Server("0A", "a1", null, null);
Server s2 = new Server("0A", null, "b2", null);
So the merged pojo should be like this.
Server merged = merge(s1, s2);// Server{ipAddr=0A, hw1=a1, hw2=b2, hw3=null}
The merge function looks like this...
public static Server merge(Server s1, Server s2) throws Exception {
Server merged = new Server();
for (Field field : Server.class.getDeclaredFields()) {
field.setAccessible(true);
Object getS1 = field.get(s1);
Object getS2 = field.get(s2);
if(getS1 == null && getS2 != null) {
field.set(merged, getS2);
} else if (getS1 != null && getS2 == null) {
field.set(merged, getS1);
} else { //equal values
field.set(merged, getS1);
}
}
return merged;
}
Here is the example code to merge three maps, Its kinda quick and dirty but works well.
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
class MergeMaps {
public static void main(String[] args) throws Exception {
Map<String, Server> map1 = new HashMap<>();
Map<String, Server> map2 = new HashMap<>();
Map<String, Server> map3 = new HashMap<>();
// Add some test data to map 1
map1.put("serv1", new Server("0A", "a1", null, null));
map1.put("serv2", new Server("0B", "b1", null, null));
System.out.println(map1);
// Add some data to map 2
map2.put("serv1", new Server("0A", null, "a2", null));
map2.put("serv2", new Server("0B", null, "b2", null));
map2.put("serv3", new Server("0C", null, "c2", null));
System.out.println(map2);
// Add some data to map 3
map3.put("serv1", new Server("0A", null, null, "a3"));
map3.put("serv2", new Server("0B", null, null, "b3"));
map3.put("serv3", new Server("0C", null, null, "c3"));
map3.put("serv4", new Server("0D", null, null, "d4"));
System.out.println(map3);
Map<String, Server> resultingMap = new HashMap<>();
resultingMap.putAll(map1);
for (Map.Entry<String, Server> entry : map2.entrySet()) {
if (resultingMap.containsKey(entry.getKey())) {
Server s = resultingMap.get(entry.getKey());
Server t = entry.getValue();
Server merged = merge(s, t);
resultingMap.put(entry.getKey(), merged);
} else {
resultingMap.put(entry.getKey(), entry.getValue());
}
}
for (Map.Entry<String, Server> entry : map3.entrySet()) {
if (resultingMap.containsKey(entry.getKey())) {
Server server1 = resultingMap.get(entry.getKey());
Server server2 = entry.getValue();
Server merged = merge(server1, server2);
resultingMap.put(entry.getKey(), merged);
} else {
resultingMap.put(entry.getKey(), entry.getValue());
}
}
System.out.println(resultingMap);
}
public static Server merge(Server s1, Server s2) throws Exception {
Server merged = new Server();
for (Field field : Server.class.getDeclaredFields()) {
field.setAccessible(true);
Object getS1 = field.get(s1);
Object getS2 = field.get(s2);
if (getS1 == null && getS2 != null) {
field.set(merged, getS2);
} else if (getS1 != null && getS2 == null) {
field.set(merged, getS1);
} else {
field.set(merged, getS1);
}
}
return merged;
}
}
class Server {
private String ipAddr;
private String hw1;
private String hw2;
private String hw3;
public Server() {
}
public Server(String ipAddr, String hw1, String hw2, String hw3) {
this.ipAddr = ipAddr;
this.hw1 = hw1;
this.hw2 = hw2;
this.hw3 = hw3;
}
//Getter and setters
#Override
public String toString() {
return "Server{" + "ipAddr=" + ipAddr + ", hw1=" + hw1 + ", hw2=" + hw2 + ", hw3=" + hw3 + '}';
}
}
The output looks like this..
{serv2=Server{ipAddr=0B, hw1=b1, hw2=null, hw3=null}, serv1=Server{ipAddr=0A, hw1=a1, hw2=null, hw3=null}}
{serv2=Server{ipAddr=0B, hw1=null, hw2=b2, hw3=null}, serv3=Server{ipAddr=0C, hw1=null, hw2=c2, hw3=null}, serv1=Server{ipAddr=0A, hw1=null, hw2=a2, hw3=null}}
{serv2=Server{ipAddr=0B, hw1=null, hw2=null, hw3=b3}, serv3=Server{ipAddr=0C, hw1=null, hw2=null, hw3=c3}, serv4=Server{ipAddr=0D, hw1=null, hw2=null, hw3=d4}, serv1=Server{ipAddr=0A, hw1=null, hw2=null, hw3=a3}}
{serv2=Server{ipAddr=0B, hw1=b1, hw2=b2, hw3=b3}, serv3=Server{ipAddr=0C, hw1=null, hw2=c2, hw3=c3}, serv4=Server{ipAddr=0D, hw1=null, hw2=null, hw3=d4}, serv1=Server{ipAddr=0A, hw1=a1, hw2=a2, hw3=a3}}
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.
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);
}
}
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();
}
}
}