HashMap example
package com.ram; import java.util.HashMap; import java.util.Iterator; public class HashMapExample { public static void main(String[] args) { HashMapmap = new HashMap (); //Men's ATP rankings as of 2014 map.put(1, "Nadal"); map.put(2, "Djokovic"); map.put(3, "Ferrer"); map.put(4, "Murray"); map.put(5, "Del Porto"); map.put(6, "Federer"); //Get the size of HashMap System.out.println("Size of of HashMap: "+map.size()); //Returns value if key is present System.out.println(map.get(2)); //Retrieve values from HashMap Iterator it = map.keySet().iterator(); while(it.hasNext()){ Integer key = it.next(); System.out.println(map.get(key)+" rank is : "+key); } //Returns true if the value is present System.out.println(map.containsValue("Murray")); //Returns true if key is present System.out.println(map.containsKey(6)); //Removes key and its corresponding value if the key is present System.out.println("Removed "+map.remove(3)); //Removes all mappings from map map.clear(); } }
Execute HashMapExample class and you get the below output:
Size of of HashMap: 6
Djokovic
Nadal rank is : 1
Djokovic rank is : 2
Ferrer rank is : 3
Murray rank is : 4
Del Porto rank is : 5
Federer rank is : 6
true
true
Removed Ferrer
Size of of HashMap: 6
Djokovic
Nadal rank is : 1
Djokovic rank is : 2
Ferrer rank is : 3
Murray rank is : 4
Del Porto rank is : 5
Federer rank is : 6
true
true
Removed Ferrer
No comments:
Post a Comment