Core java interview Questions You'll Most Likely Be Asked (Second Edition)


How does the Map.getOrDefault method work?


Download 1.52 Mb.
Pdf ko'rish
bet98/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   94   95   96   97   98   99   100   101   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

How does the Map.getOrDefault method work?
Answer:
Java 8 has added the getOrDefault method to the Map
interface. It accepts as parameter the key whose value needs to
be retrieved as well as a default value. So, it returns a value
corresponding to the specified key if present, otherwise, it returns
the default value passed in. The following code snippet
demonstrates this:
Map fruits = new HashMapString>();
fruits.put(1,”Apple”);
fruits.put(2,”Orange”);


255.
String fruit1 = fruits.getOrDefault(1,”Mango”);
//returns apple
String fruit2 = fruits.getOrDefault(3,”Mango”);
//returns mango
This code creates a map called fruits with an Integer key and
a String value. It adds some values to the map. It first uses the
getOrDefault method to retrieve the value corresponding to
the key 1 passing the default value as Mango. Since there is a
value in the Map with key 1, fruit1 is assigned the value
corresponding to the key which is Apple. It then uses the
getOrDefault method to retrieve the value corresponding to
the key 3 passing the default value as Mango. Since there is no
value in the map with key 3, fruit2 is assigned the default
value Mango.
What is the output of the following code snippet?
Map fruits = new HashMapString>();
fruits.put(1,”Apple”);
fruits.put(2,”Orange”);
fruits.put(3,”Strawberry”);
fruits.replace(1, “Mango”); //Line 1
fruits.replace(2, “Orange”,”Banana”); //Line 2
fruits.replace(3, “Blackberry”,”Pineapple”); //Line 3
System.out.println(fruits.get(1));
System.out.println(fruits.get(2));
System.out.println(fruits.get(3));
Answer:
This code prints the following output:


256.



Mango
Banana
Strawberry
The Map.replace(key, value) method replaces a value
only if it is mapped to a value. In the above example, the key 1 is
mapped to the value Apple, so the replace() method replaces
the value Apple with the value Mango. The
Map.replace(key, oldValue, newValue) replaces a
value only if it is mapped to the specified value. In the above
example, the key 2 is mapped to the value Orange. So, the
replace method at Line 2 replaces the value Orange with the
value Banana. Also, the key 3 is mapped to the value

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   94   95   96   97   98   99   100   101   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling