简体   繁体   中英

Retrieving the keys of Hashmap

I am trying to retrieve the keys of hashmap.

I am using to hashmap as follows:

HashMap<String, String> inner = new HashMap<String, String>();
HashMap<HashMap<String,String>, String> outer = new HashMap<HashMap<String,String>, String>();

I am putting values in both the hashmap as follows:

inner.put("1", "one");
inner.put("2", "two");
inner.put("3", "three");

outer.put(inner, "outer1");
outer.put(inner, "outer2");

Now I want to get the output as

1 one outer1
1 one outer2
2 two outer1
2 two outer2
3 three outer1
3 three outer2

But I am unable to get this. Can you please help me to solve this.

Edited code:

HashMap<String, String> inner = new HashMap<>();
HashMap<String, String> inner1 = new HashMap<>();
HashMap<HashMap<String, String>, String> outer = new HashMap<>();

outer.put(inner, "outer1");
outer.put(inner1, "outer2");

inner1.put("1", "one");
inner1.put("2", "two");
inner1.put("3", "three");
inner1.put("4", "three");

inner.put("1", "one");
inner.put("2", "two");
inner.put("3", "three");
inner.put("4", "three");

 outer.forEach((k,v) -> {
    k.forEach((k1, v1) -> System.out.println(k1 + " " + v1 + " " + v));
});

As I mentioned in the comments, the second put over outer will override the first put (the key is the same in both). Apart from that, one way to print out what you want could be as follows:

outer.forEach((k,v) -> {
    k.forEach((k1, v1) -> System.out.println(k1 + " " + v1 + " " + v));
});

Just iterate over the outer hash map and iterate again over each key (inner hashmap).

Hope it helps.

You can use this way this work with me:

    for (HashMap<String, String> key : outer.keySet()) {
        for (String key2 : key.keySet()) {
            System.out.println(key2 + " " + key.get(key2) + " " + outer.get(key));
        }

Or this way:

outer.keySet().stream().forEach((key) -> {
    key.keySet().stream().forEach((key2) -> {
        System.out.println(key2 + " " + key.get(key2) + " " + outer.get(key));
    });
});

But you can't get the result you want, because you put in your HashMap the same KEY , so the HshMap replace the key and values.

If you desplay the size of your HashMap you will find just one not two:

System.out.println(outer.size());

So the Correct result

1 one outer2
2 two outer2
3 three outer2

Wrong result

1 one outer1
1 one outer2
2 two outer1
2 two outer2
3 three outer1
3 three outer2

So if you want to get what you want you should to change the key, like to add another thing to the first HashMap

inner.put("1", "one");
inner.put("2", "two");
inner.put("3", "three");

outer.put(inner, "outer1");
inner.put("4","three");
outer.put(inner, "outer2");

Hope this can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM