简体   繁体   中英

Creating Hashmap using existing hashmap

I created a hashmap as shown below:

Map<String, String> streetno = new HashMap<String, String>();

streetno.put("3", "Sachin");
streetno.put("2", "Dravid");
streetno.put("1", "Sehwag");
streetno.put("5", "Laxman");
streetno.put("4", "Kohli");

Now I want to create a new hashmap where key of the above hashmap becomes value and value becomes key as shown below:

Map<String, String> streetname = new HashMap<String, String>();

streetname.put("Sachin", "3");
streetname.put("Dravid", "2");
streetname.put("Sehwag", "1");
streetname.put("Laxman", "5");
streetname.put("Kohli", "4");

I don't know how to do that.. Can anyone help me out with this..

Map<String, String> streetname = new HashMap<String, String>();

for (Entry<String,String> e : streetno.entrySet()) {
  streetname.put(e.getValue(), e.getKey());
}

Here, the for loop iterates over all entries (ie key/value pairs) in the original map, and inserts them into the second map with the key and value swapped over.

It is probably a good idea to check that put() returns null . If you get a non-null value, this means that the values in streetno are not unique. Since this is homework, I leave it to you to figure out the consequences, and how best to handle this.

Perfect you are almost there. Now you need to iterate the first hash map keys and simulate what you have done in those 5 lines:

streetname.put("Sachin", "3");
streetname.put("Dravid", "2");
streetname.put("Sehwag", "1");
streetname.put("Laxman", "5");
streetname.put("Kohli", "4");

Tip: iteration over map might be a bit tricky for you, but usually it is done like that:

for (String key : streetno.keySet()) {
...
}

Good luck with your homework!

Java 8:

Map<String, String> streetname = 
    streetno.entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));

Note:

If you are tempted to use parellelstream() instead of stream() think twice about it. This would only be appropriate if your Map is extremely large.

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