Iterate through nested map - java

I have a nested hashmap (Hashmap inside a hashmap).
Map<String,Map<String,String>> test = new HashMap<String,Map<String,String>>();
Map<String,String> testMp = new HashMap<String,String>();
testMp.put("1", "Key1");
testMp.put("2", "Key2");
testMp.put("3", "Key3");
testMp.put("4", "Key4");
testMp.put("5", "Key4");
test.put("One", testMp);
Ideally if I need to print the key and the values in the test map, I'd do this -
for(Map.Entry<String, Map<String,String>> t:test.entrySet()) {
System.out.println("KEY: " +t.getKey()+ " VALUE:" +t.getValue());
}
But I want the key and the value of the inner map as well. I want something like this -
Key of outermap
Key of innermap, and its value.

Then do a nested loop :
for(Map.Entry<String, Map<String,String>> t:test.entrySet()) {
String key = t.getKey();
for (Map.Entry<String,String> e : t.getValue().entrySet())
System.out.println("OuterKey: " + key + " InnerKey: " + e.getKey()+ " VALUE:" +e.getValue());
}
or
for(Map.Entry<String, Map<String,String>> t:test.entrySet()) {
System.out.println(t.getKey());
for (Map.Entry<String,String> e : t.getValue().entrySet())
System.out.println("KEY: " + e.getKey()+ " VALUE:" +e.getValue());
}

Write a recursive method which will call itself when it encounters that the entry to corresponding key is a map.

Related

Hashmap not returning value as expected when retrieving using key

Should be simple enough but it's driving me nuts!
Have a HashMap with a Key:Value pair as Long:Dto respectively.
When I debug, I can see the one entry in the Hashmap with a Long value as the key - but when I try a get() using the Key, I'm getting a null back.
For the following:
Map<Long, Dto> response = getMap();
System.out.println("Contents of HashMap: " + response);
System.out.println("Size of HashMap: " + response.size());
System.out.println("HashMap Keyset: " + response.keySet());
System.out.println("HashMap Contains: " + response.containsKey(19999984L));
System.out.println("HashMap Object: " + response.get(19999984L));
I'm getting the following output:
Contents of HashMap: {19999984={productOptionId=19999984, amount={amount=20.99, currency=EUR}, pricingType=MSRP}}
Size of HashMap: 1
HashMap Keyset: [19999984]
HashMap Contains: false
HashMap Object: null
Any suggestions would be appreciated here... this should work surely!
Maybe I'm missing something obvious.
Answer: So it seems my key value is of String type - as below:
System.out.println("Contents of HashMap: " + response);
System.out.println("Size of HashMap: " + response.size());
System.out.println("HashMap Keyset: " + response.keySet());
System.out.println("HashMap Contains: " + response.containsKey("19999984"));
System.out.println("HashMap Object: " + response.get("19999984"));
System.out.println("HashMap Class: " + response.getClass());
Your key in the hashmap is a int type and your contains method has 19999984L which is long type.
Contents of HashMap: {19999984={productOptionId=19999984, amount={amount=20.99, currency=EUR}, pricingType=MSRP}}
Size of HashMap: 1
System.out.println("HashMap Contains: " + response.containsKey(19999984L));
That's the reason for false.

Compare Hashmap String value and duplicate key for Repeated entry

I am using
Map<Integer, String> adi = new HashMap<Integer, String>();
for(int u=0; u< sari_nodes.size();u++){
adi.put(u, sari_nodes.get(u));
}
for (Map.Entry<Integer, String> entry : adi.entrySet()) {
tv.setText(tv.getText()+"Key : " + entry.getKey()+ " Value : " + entry.getValue()+"\n");
}
My output is :
key: 0 Value : cat
key: 1 Value : dog
key: 2 Value : car
key: 3 Value : car
key: 4 Value : car
key: 5 Value : car
I want to repeat the key for same entry so that my output looks like
key: 0 Value : cat
key: 1 Value : dog
key: 2 Value : car
key: 2 Value : car
key: 2 Value : car
key: 2 Value : car
How can I perform a check to get these kind of repeated keys?
Can somebody give me some guidance on solving this issue?
thanks.
I second the answer of NameSpace.
You want every value to be unique. So, for that you can create a map which add value of your current map as a key. Ultimately we are trying to fetch the same key (first key) for same values. You can do it in a following way.
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "cat");
map.put(2, "dog");
map.put(3, "car");
map.put(4, "cat");
map.put(5, "dog");
map.put(6, "dog");
Map<String, Integer> uniqueValues = new HashMap<>();
for (Entry<Integer, String> entry : map.entrySet()) {
Integer key = entry.getKey();
String val = entry.getValue();
if (uniqueValues.containsKey(val)) {
key = uniqueValues.get(val);
}
uniqueValues.put(val, key);
System.out.println("Key : " + key + " - Value : " + val);
}
OUTPUT
Key : 1 - Value : cat
Key : 2 - Value : dog
Key : 3 - Value : car
Key : 1 - Value : cat
Key : 2 - Value : dog
Key : 2 - Value : dog
NOTE : Case sensitive, in above code it will consider that Dog and dog both are different.
You would just make a second map, and as you iterate through the elements of the first map, flip the key-value to be the value-key of the second map. If first map's value has already been added to second map as a key, do not overwrite, and output the key-stored-as-a-value in the latter, otherwise output the new key.
You can try this code below:
Map<Integer, String> adi = new HashMap<>();
adi.put(0, "cat");
adi.put(1, "dog");
adi.put(2, "car");
adi.put(3, "car");
adi.put(4, "car");
adi.put(5, "PC");
int lastKey = 0;
String lasValue = "";
for (Map.Entry<Integer, String> entry : adi.entrySet()) {
if (!entry.getValue().equals(lasValue)) {
lastKey = entry.getKey();
}
lasValue = entry.getValue();
//tv.setText(tv.getText()+"Key : " + lastKey+ " Value : " + entry.getValue()+"\n");
System.out.println("Key : " + lastKey+ " Value : " + entry.getValue());
}
And this is the output:
Key : 0 Value : cat
Key : 1 Value : dog
Key : 2 Value : car
Key : 2 Value : car
Key : 2 Value : car
Key : 5 Value : PC

How to obtain particular value from Map in a "String" format

I have a Map :
Map<String, String> value
How to obtain particular value "String" ----> "type" from json value, how do i obtain it?
I tried below code, which only returns me KEY and not VALUE
Iterator it = payload.entrySet().iterator();
while (it.hasNext())
{
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
String key = pair.getKey().toString();
String value = pair.getValue().toString();
Log.d("getActionValue", "key : " + key);
Log.d("getActionValue", "value : + value");
}
You don't access your variable in your output, since value is still in in the string.
Change like this:
Log.d("getActionValue", "value : " + value);
Your problem is here Log.d("getActionValue", "value : + value"); it should be Log.d("getActionValue", "value : "+ value);
Try this for loop :-
for (Map.Entry<String, String> entry : payload.entrySet())
{
Log.d("getActionValue", "key : " + entry.getKey());
Log.d("getActionValue", "value :" + entry.getValue());
}
I want that particular "String" ----> "type" from value, how do i
obtain it?
payload Map contains JSONObject's as value of every key. so to get type need to first convert String to JSONObject then get value using type key:
JSONObject jsonObject=new JSONObject(value);
String strType="";
if(jsonObject.has("notification-action")){
JSONObject jsonObjectnotification=jsonObject.optJSONObject
(""notification-action"");
if(jsonObjectnotification.has("type")){
strType=jsonObjectnotification.optString("type");
}
}
You logging it wrong.
Should be:
Log.d("getActionValue", "value : " + value);

Java hashmap iterate only certain keys

I'm looking for a way to get the values for just a specific key when I get into the second loop here. I'm using snakeyaml and loading it to a Map. My yaml looks something like this:
number:
id: status.number
label: Number
contactType:
id: status.contact_type
label: Contact Type
What I'm attempting to do is just get the key and value for id. It's probably super obvious, but I haven't found a way to do so.
Map<String, Map<String, String>> a = (Map<String, Map<String, String>>) yaml.load(input);
for (Map.Entry<String, Map<String, String>> t : a.entrySet()) {
String key = t.getKey();
for (Map.Entry<String, String> e : t.getValue().entrySet()) {
System.out.println("OuterKey: " + key + " InnerKey: " + e.getKey() + " VALUE:" + e.getValue());
}
}
To get the value(s) for the "inner key", you don't need to loop through every inner map.
In the following example, I assume you already have an innerKey variable that holds the desired inner key.
Map<String, Map<String, String>> a = (Map<String, Map<String, String>>) yaml.load(input);
for (Map.Entry<String, Map<String, String>> t : a.entrySet()) {
String outerKey = t.getKey();
String innerValue = t.getValue().get(innerKey);
System.out.println("OuterKey: " + outerKey + " InnerKey: " + innerKey + " VALUE:" + innerValue);
}

build Uri string into name-value collection in java

HashMap<String, List<String>> filterableMap = new HashMap<>();
filterableMap.put("department", Arrays.asList("A","B",null));
filterableMap.put("group", Arrays.asList("C","D",null));
From the above map i need to dynamically build a queryString like show below.
"SomeURL"/token/filter?department=A&department=B&group=C&group=D
I just used Hashmap we can use any thing as long as we can hold the values in name value pair.
for (Map.Entry<String, List<String>> entry : filterableMap.entrySet()) {
String key = entry.getKey();
List<String> value = entry.getValue();
for(String aString : value){
System.out.println("key : " + key + " value : " + aString);
if("department".equalsIgnoreCase(key)) {
qStrBulderBuilder.append("department =");
qStrBulderBuilder.append(value);
}
}
}
I am using like above approach , but i need to make sure i need put "=" and "&" in the right places some times we may not get "department" or "group"

Categories

Resources