简体   繁体   中英

Printing out a HashMap using an Another HashMap's key as values

If I have a HashMap such as

{opst=post pots stop spot tops opts,
 art=rat tar art,
 glos=slog,
 gopr=gorp,
 fgor=frog,
 aprt=trap tarp part,
 dgo=dog god,
 act=act cat tac,
 fglo=flog golf}

and a HashMap such as

{opst=otsp, art=atr, fgor=grof, aprt=arpt, dgo=gdo, act=atc}

How would I use the second HashMap as my key to print out something like...

arpt part tarp trap
atc act cat tac
atr art rat tar
gdo dog god
grof frog
otsp opts post pots spot stop tops

Assuming your first HashMap is called firstMap and the second is secondMap , then navigate through the keys of secondMap to print the values stored on first map. Here's a code sample:

for (String secondMapKey : secondMap.keySet()) {
    System.out.println(firstMap.get(secondMapKey));
}

Another option may be iterating through the entries of secondMap of the second map and get the keys (in case you also need the value of secondMap along to the key):

for (Map.Entry<String, String> entry : secondMap.entrySet()) {
    System.out.println(firstMap.get(entry.getKey()) + " " + entry.getValue());
}

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