Java 11 Certification Practice Questions (For the complete list, refer http://talks.skilltoz.com/java-11-certification-exam-questions/)
How do we get a value from a HashMap?
Let us see an example.
Map<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "Text1"); map.put(2, "Text2"); String s = map.get(2); System.out.println(s); // Prints Text2 String s0 = map.get(0); System.out.println(s0); // Prints null
In the above code, the key 1 is mapped to the value “Text1” and the key 2 is mapped to “Text2”. Invoking the get() method passing the key 2 will return “Text2”. However, passing the key 0 will return null, because no such key exists in the map.
Is it possible to set a default value for non-existing keys?
If you want to return a default value if the passed key does not exist in the HashMap, use the getOrDefault() method. We need to pass a default value as the second argument to this method.
If the key exists in the HashMap, the getOrDefault() method works just like the get() method and returns the corresponding value. If the key doesn’t exist, then the default value will be returned instead of null.
Let us see the below code to understand it better.
String s1 = map.getOrDefault(1, "Default"); System.out.println(s1); // Prints "Text1" String s2 = map.getOrDefault(0, "Default"); System.out.println(s2); // Prints "Default"
First, 1 is passed as the first argument to the getOrDefaut() method. As the key 1 already exists in the map, the corresponding value “Text1” is obtained in s1. Secondly, 0 is passed and as there is no such key in the HashMap, the getOrDefault() method returns the default value passed as the second argument. Hence, “Default” is obtained in s2.
Q1. What will be the result?
Map<Integer, String> map = new HashMap<Integer, String>(); int i = 1; map.put(i, "Text1"); map.put(i, "Text2"); String s = map.getOrDefault(i++, null); System.out.println(s);
For answers to the above question and other questions on Map, visit https://thinkassess.com/java/maps-in-java-quiz/