Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
[JAVA] Cool thing about iterating a map with iterator.
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { // The set supports element removal, which removes the corresponding mapping from the map, // via the Iterator.remove(), Set.remove(), removeAll(), retainAll(), and clear() operations, // BUT --> It does not support the add() or addAll() operations. // ---> and that makes sense as you can only add "key" in here there is no key-Valu in the set // BUT ---> WHAT ABOUT THE entySet().... hmmm ---> MOST PROBABLY ITS NOT == CONFIRMED public static void main(String args[]) { HashMap<String, Integer> priceMap = new HashMap<>(); priceMap.put("car", 1394870); // in $'s yup priceMap.put("vacation", 2938793); priceMap.put("buisness", 2387894); priceMap.put("experience",92840478 ); priceMap.put("gadgets", 1472933443); Set<String> keySet = priceMap.keySet(); // Iterating using keySet() method of HashMap for(String key: keySet){ // Iterating using foreach loop Integer value = priceMap.get(key); System.out.printf("key: %s, ----- value: %d %n", key, value); } System.out.println("\n\n\n\n"); //----- Trying to change the map enteries via iterator, or the set we got ------ // removing an elements mapping from the priceMap using iterator & keySet (a set we got) keySet.remove("car"); // REMOVED CAR Iterator<String> itr = keySet.iterator(); while(itr.hasNext()){ String key = itr.next(); int price = priceMap.get(key).intValue(); if(key.equals("gadgets")){ itr.remove(); // doesn't take an argument System.out.println("key : " + key + " === price : " + price + "\t\t** REMVED **" ); } else System.out.println("key : " + key + " === price : " + price ); } // final keySet -> overrides toString() System.out.println("\n\n\nfinal keySet : " + keySet); // final MAP -> overrides toString() System.out.println("\n\n\nfinal map (priceMap) : \n" + priceMap + "\t<<-- see all the changes are preserved"); // BUT --> It does not support the add() or addAll() operations. keySet.add("anything"); // Exception in thread "main" java.lang.UnsupportedOperationException <<-------- } }
run
|
edit
|
history
|
help
0
pre
JAVA # Boşluklu bir metinde kaç adet boşluk var
Coding Numbers - Duplicate - HashSet
Draw rectangle using for loop
SecToHours
laba3
JAVA # Rastgele 15 sayıdan oluşan bir dizinin EK-EB ve Ortalamasını bulan Java Kodu
My date and time
String
queue_using_stack