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..
Here, the
forloop iterates over all entries (i.e. 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()returnsnull. If you get a non-null value, this means that the values instreetnoare not unique. Since this is homework, I leave it to you to figure out the consequences, and how best to handle this.