I am new to Java.
I have a map like this.
HashMap<String,HashMap<String,String>>mp;
How to traverse through this?
mp has another inside it.
I know the normal way of traversing through the map using entrySet;
You traverse the outer map using entrySet, then for each value of the outer map you traverse the inner map using entrySet.
for (Map.Entry<String,HashMap<String,String>> entry : mp.entrySet()) {
for (Map.Entry<String,String> innerEntry : entry.getValue().entrySet()) {
...
}
}
You can try this code:
package com.test;
import java.util.HashMap;
import java.util.Set;
public class TestMain {
public static void main(String[] args) {
HashMap<String,HashMap<String,String>>mp= new HashMap<String,HashMap<String,String>>();
HashMap<String, String> innerMap1= new HashMap<String, String>();
innerMap1.put("1", "firstValueOf_InnerMap1");
innerMap1.put("2", "SecondValueOf_InnerMap1");
HashMap<String, String> innerMap2= new HashMap<String, String>();
innerMap2.put("1", "firstValueOf_InnerMap2");
innerMap2.put("2", "SecondValueOf_InnerMap2");
mp.put("one", innerMap1);
mp.put("two", innerMap2);
for (HashMap<String,String> innerHashMap : mp.values()) {
for (String value : innerHashMap.values()) {
System.out.println(value);
}
}
}
}
You can try this code:
Set hmset = hm.entrySet();
for (HashMap<String,String> innerMap : hm.values()) {
for (String st1 : innerMap.values()) {
System.out.println(st1);
}
}
Related
Here's my first Java class, which includes the TreeMap that I want to loop through:
package myFunctions;
import java.util.TreeMap;
public class myUrls {
public void main() {
TreeMap<String, String> getUrl = new TreeMap<String, String>();
getUrl.put("app1", "URL 1");
getUrl.put("app2", "URL 2");
}
// Print keys and values
for (String i : getUrl.keySet()) {
System.out.println("app name: " + i + " url: " + getUrl.get(i));
}
}
}
Here's my second class, where I want to take the previously mentioned TreeMap and loop through it:
package myFunctions;
public anotherClass() {
DA_devurl myUrls = new DA_devurl();
//Loop through the array and perform seperate actions for each keyvalue pair
}
In your first class, I recommend making your TreeMap a private instance variable with a getter method:
package functions;
import java.util.TreeMap;
public class MyUrls {
private TreeMap<String, String> getUrl;
public MyUrls() {
getUrl = new TreeMap<String, String>();
}
public void main() {
getUrl.put("app1", "URL 1");
getUrl.put("app2", "URL 2");
}
public TreeMap<String, String> getGetUrl() {
return this.getUrl;
}
}
Now, in your second class, all you need to do is call the getter method after creating an instance of your previous class, and then looping through its entries with the proper syntax:
package functions;
import java.util.TreeMap;
import java.util.Map;
public class AnotherClass {
public static void main(String args[]) {
MyUrls myUrl = new MyUrls();
// populates the TreeMap
myUrl.main();
TreeMap<String, String> urls = myUrl.getGetUrls();
// Loop through the array and perform seperate actions for each keyvalue pair
for (Map.Entry<String, String> entry : urls.entrySet()) {
// do something with entry.getKey() and entry.getValue()
}
}
}
I am not able get the code to go to else block. The code always goes inside if block. Is there a way to validate the value of a Map<String, Map<String,String>>.
I get compile warning Map<String, Map<String, String>> may not contain values of type String.
Could anyone please tell me how to validate this?
public class TestClass {
Map<String, String> map = new HashMap<String, String>();
Map<String, Map<String, String>> val= new HashMap<String, Map<String, String>>();
public void setData() {
map = new HashMap<String, String>();
map.put("10", "1000");
map.put("11", "alphabet");
map.put("12", "1002");
map.put("13", "1003");
val.put("1", map);
val.put("2", map);
val.put("3", map);
val.put("4", map);
}
public void showData() {
if (!this.val.containsValue("alphabet")) {
System.out.println("inside if ");
} else {
System.out.println("else");
}
}
public static void main(String args[]) {
TestClass obj = new TestClass();
obj.setData();
obj.showData();
}
}
I have a Map and a HashSet.
The goal is to check the contents of the Set against the Map and add it to the Map if the elements are there in the HashSet but not in the Map.
// Map is defined in a class
private final Map<String, A> sb = new ConcurrentHashMap<>();
public void someMethod() {
Set<A> hSet = new HashSet<>();
for (A a : ab){
hSet.add(a..a...);
// Check if all elements added to hash Set are there in a Map
// if not present, add it to Map
}
}
if you want to search in map values:
if(!map.values().contains(a))
// put a in the map
if you want to look for keys
if(!map.containsKey(a))
// put a in the map
keep in mind that contains calls equals so in your A class you have to implement hashCode and equals.
public static void main(String[] args) {
Set<String> set = Stream.of("a","b","c","d").collect(Collectors.toSet());
Map<String, String> map = new HashMap<String, String>();
map.put("a", "foo");
map.put("h", "bar");
map.put("c", "ipsum");
for (String string : set) {
if(!map.containsKey(string)) {
map.put(string,string);
}
}
System.out.println(map);
}
output
{a=foo, b=b, c=ipsum, d=d, h=bar}
for (String element : hSet) {
if (!sb.containsKey(element)) {
sb.put(element, A);
}
}
Following could also be solution:
private final Map<String, A> sb = new ConcurrentHashMap<>();
public void someMethod() {
Set<String> set = new HashSet<>();
set.stream().filter(word -> !sb.containsKey(word))
.forEach(word -> sb.put(word, correspondingValueOfTypeA));
}
I am new to hash mapping and I was trying to created a nested hash map on one side of the class and create another class to call it out, so here's how my code looks like
public class Hash {
private HashMap<String, HashMap<String, String>> wow = new HashMap<String, HashMap<String, String>>();
public void SetHash(){
wow.put("key", new HashMap<String, Object>());
wow.get("key").put("key2", "val2");
}
public HashMap GetMap(){
return wow;
}
}
And on the other class which is the main class it will be like this:
public static void main(String[] args) {
Hash h = new Hash();
h.SetHash();
System.out.println(h.GetMap.get("key").get("key2"));
}
But when I place the second get, there's an error, so I am not sure if this is possible or if I should actually place the hash directly at the main class.
GetMap is a method, not an attribute, so you have to refer it with parenthesis ():
h.GetMap().get("key")
Now, second error. Your Map<String, Map<String, String> named wow contains a values that are objects of the type Map<String, String> so, before the get, you need get the map:
Map<String, String> m = (HashMap<String, String>) h.GetMap().get("key");
And then you can print it:
System.out.println(m.get("key2"));
if you want an ONELINER (is not really clear, but check explanation in comments):
System.out.println(((HashMap<String, String>) h.GetMap().get("key")).get("key2"));
// ↑ casting parenthesis ↑ (
// ↑ this say group IS a map and allow get() ↑
// ↑ system.out.println parenthesis ↑
NOTE: change also this declaration
wow.put("key", new HashMap<String, Object>());
By
wow.put("key", new HashMap<String, String>());
FINAL CODE:
public class Q37066776 {
public static void main(String[] args) {
Hash h = new Hash();
h.SetHash();
Map<String, String> m = (HashMap<String, String>) h.GetMap().get("key");
System.out.println(m.get("key2"));
}
}
class Hash {
private HashMap<String, HashMap<String, String>> wow = new HashMap<String, HashMap<String, String>>();
public void SetHash() {
wow.put("key", new HashMap<String, String>());
wow.get("key").put("key2", "val2");
}
public HashMap GetMap() {
return wow;
}
}
WORKING ONLINE DEMO
but you can always
Do it better! :=)
As pointed by Andrew
you can change return of the method,
But also many other things like:
using less concrete objects (Map instead of HashMap)
follow conventions (GetMap() would be getMap())
Make Hash a static class with static block
If I had to rewrite your code, my result would be like this:
public class Q37066776 {
public static void main(String[] args) {
System.out.println(Hash.getMap().get("key").get("key2"));
}
}
class Hash {
private static Map<String, Map<String, String>> wow = new HashMap<String, Map<String, String>>();
static {
wow.put("key", new HashMap<String, String>());
wow.get("key").put("key2", "val2");
}
public static Map<String, Map<String, String>> getMap() {
return wow;
}
}
You have 3 errors:
GetMap is a method - you need to write GetMap().
you declared the inner Map as HashMap<String, String> - you cannot initialize the inner map to: wow.put("key", new HashMap<String, Object>());
Change it to wow.put("key", new HashMap<String, String>());
In order to access the inner map from the main - you must declare the returned value of GetMap to be Map<String, HashMap<String, String>> instead of just raw type. Otherwise, the outer class won't know that the outer map value is also a hash map.
Instead of using nested maps, you should use google's Guava Table:
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html
I have a hashmap used to store the platform details
I need to iterate Map<String, Map<String, String>> finalmapWin8
and get the values and keys of mapWin8
values 33,8 and key BrowserType.CHROME, BrowserType.FIREFOX and BrowserType.IE
Also i want to get the key of 'finalmapWin8' "WIN8_1"
How can i iterate Map<String, Map<String, String>> finalmapWin8
static Map<String, Map<String, String>> finalmapWin8 = new HashMap<Platform, Map<String, String>>();
public static final Map<String, String> mapWin8 = new HashMap<String, String>();
static {
mapWin8.put(BrowserType.CHROME, "33");
mapWin8.put(BrowserType.FIREFOX, "33");
mapWin8.put(BrowserType.IE, "8");
}
static {
finalmapWin8.put("WIN8_1", mapWin8);
}
iteration for Map is the same. since your value for your map is also a Map then you just need another iteration to iterate through it.
for(String s: finalmapWin8.keySet()){
System.out.println(s + " : ");
for(Entry<String, String> entry : finalmapWin8.get(s).entrySet()){
System.out.println(entry);
}
}
You can use a for loop for loop for Map of type Map.Entry<String, Map<String, String>> ... well, that's it.. See the code snippet below -
import java.util.HashMap;
import java.util.Map;
public class Test {
static Map<String, Map<String, String>> finalmapWin8 = new HashMap<String, Map<String,String>>();
public static final Map<String, String> mapWin8 = new HashMap<String, String>();
static {
mapWin8.put("CHROME", "33");
mapWin8.put("FIREFOX", "33");
mapWin8.put("IE", "8");
}
static {
finalmapWin8.put("WIN8_1", mapWin8);
}
public static void main(String[] args) {
for(Map.Entry<String, Map<String, String>> entry : finalmapWin8.entrySet()) {
System.out.println(entry.getValue());
}
}
}
// get the keysets or outer map and then again run a secound loop for inner map.
for (Map.Entry<String, Map<String, String>> entry : firstMap) {
system.out.println("entry="+entry );
}
Refer to How to efficiently iterate over each Entry in a Map?
You can use below code for iterating through HashMap
for (Map.Entry<String, Map<String, String>> entry : finalmapWin8.entrySet()) {
System.out.println("Key:"+entry.getKey());
for (Map.Entry<String, String> entry1 : mapWin8.entrySet()) {
System.out.println("Keys in Second:"+ entry1.getKey()+" Values:"+ entry1.getValue());
}
}