Saturday, November 23, 2019

Keyset() Vs Entryset Vs Values() Example Inwards Coffee Map

The java.util.Map interface provides 3 methods keySet(), entrySet() in addition to values() to retrieve all keys, entries (a key-value pair), in addition to values. Since these methods straight come upwardly from the Map interface, you lot tin plow over the axe role it amongst whatsoever of the Map implementation degree e.g. HashMap, TreeMap, LinkedHashMap, Hashtable, ConcurrentHashMap, and fifty-fifty amongst specialized Map implementations similar EnumMap, WeakHashMapand IdentityHashMap. In guild to travel a adept Java developer, it's of import to sympathize in addition to retrieve key classes Java API e.g. Java's Collection framework. In this article, nosotros volition non exclusively larn the difference betwixt keySet(), entrySet() in addition to values() methods, merely likewise larn how to role them inwards Java plan yesteryear looking at a elementary example.


The keySet() method

This method returns a Set persuasion of all the keys inwards the map. The fix is backed yesteryear the map, in addition to thus changes to the map are reflected inwards the set, in addition to vice-versa. If the map is modified spell an iteration over the Set is inwards progress (except through the iterator's ain withdraw operation), the results of the iteration are undefined.

The fix supports chemical ingredient removal, which removes the corresponding mapping from the map, via the Iterator.remove(), Set.remove(), removeAll(), retainAll(), in addition to clear() operations, merely It does non back upwardly the add() or addAll() operations.



You tin plow over the axe likewise role the keySet() method to iterate over a Java HashMap equally shown inwards the next example:

// Iterating using keySet() method of HashMap Set<String> keys = priceMap.keySet();         for(String key: keys){    Integer value = priceMap.get(key);    System.out.printf("key: %s, value: %d %n", key, value); }  Output: key: Car, value: 20000  key: Phone, value: 200  key: Bike, value: 6000  key: Furniture, value: 700  key: TV, value: 500 


The entrySet() method

The entrySet() method of Map interface returns a Set persuasion of the mappings contained inwards this map. The fix is backed yesteryear the map, in addition to thus changes to the map are reflected inwards the set, in addition to vice-versa.

If the map is modified spell an iteration over the fix is inwards progress (except through the iterator's ain withdraw operation, or through the setValue() functioning on a map entry returned yesteryear the iterator) the results of the iteration are undefined.

The Set likewise supports chemical ingredient removals, which removes the corresponding mapping from the map, via the Iterator.remove(), Set.remove(), removeAll(), retainAll(), in addition to clear() operations. It does non back upwardly the add() or addAll() operations.

You tin plow over the axe likewise read Core Java for the Impatient yesteryear Cay S. Horstmann to larn most dissimilar views of Collection inwards Java. One of the best books to larn Java programming at the moment. It likewise covers Java SE 8.

 Since these methods straight come upwardly from the Map interface keySet() vs entrySet vs values() Example inwards Java Map



Here is an instance of how you lot tin plow over the axe traverse over a Map inwards Java using the entrySet() method. This is yesteryear far the most efficient agency of iterating over Map out of several ways nosotros accept discussed earlier.

// traversing Map using entrySet() method Set<Entry<String, Integer>> entries = priceMap.entrySet();          for(Map.Entry<String, Integer> entry : entries){    String key = entry.getKey();    Integer value = entry.getValue();    System.out.printf("key: %s, value: %d %n", key, value); }


The values() methods

The values() methods of Map interface returns a Collection persuasion of the values contained inwards this map. The collection is backed yesteryear the map, in addition to thus changes to the map are reflected inwards the collection, in addition to vice-versa.

If the map is modified spell an iteration over the collection is inwards progress (except through the iterator's ain withdraw operation), the results of the iteration are undefined. The collection supports chemical ingredient removal, which removes the corresponding mapping from the map, via the Iterator.remove(), Collection.remove(), removeAll(), retainAll() in addition to clear() operations.

Similar to keySet() in addition to entrySet(), It does non back upwardly the add() or addAll() operations.

Here is how you lot tin plow over the axe acquire all the values from a Map inwards Java:

Collection<Integer> values = priceMap.values();

Here is prissy slid of summarizing dissimilar views of Map interface inwards Java:

iterate over the Set to impress the mapping, or withdraw whatsoever specific mapping depending upon to a greater extent than or less job organisation logic.


Java Program to role keySet(), entrySet() in addition to values()

import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set;  /**  * Java Program to demonstrate how to role keySet(), values() in addition to entrySet()  * method of HashMap.  *  * @author WINDOWS 8  *  */ public class HashMapDemo {      public static void main(String[] args) {          Map<String, Integer> priceMap = new HashMap<>();          priceMap.put("TV", 500);         priceMap.put("Phone", 200);         priceMap.put("Car", 20000);         priceMap.put("Bike", 6000);         priceMap.put("Furniture", 700);          System.out.println("price map: " + priceMap);          Set<String> keys = priceMap.keySet();         Collection<Integer> values = priceMap.values();         Set<Entry<String, Integer>> entries = priceMap.entrySet();          System.out.println("keys of Map : " + keys);         System.out.println("values from Map :" + values);         System.out.println("entries from Map :" + entries);      }  }  Output: toll map: {Car=20000, Phone=200, Bike=6000, Furniture=700, TV=500} keys of Map : [Car, Phone, Bike, Furniture, TV] values from Map :[20000, 200, 6000, 700, 500] entries from Map :[Car=20000, Phone=200, Bike=6000, Furniture=700, TV=500]


That's all most keySet() vs entrySet() vs values() method inwards Java. You accept learned how you lot tin plow over the axe obtain a dissimilar persuasion from your Map inwards Java. This technique is applicable to all Map implementation including HashMap in addition to ConcurrentHashMap. You tin plow over the axe role these methods to iterate over Map equally good equally for removing entries from Map inwards Java.

Btw, you lot should endure mindful that these methods render collections that tin plow over the axe endure modified automatically when the underlying collection changes. This tin plow over the axe practice thread-safety issues inwards concurrent Java programs. You tin plow over the axe farther read Core Java Volume 1 - Fundamentals yesteryear Cay S. Horstmann to larn most this sophisticated technique of providing persuasion instead of creating split upwardly Map classes. 

Further Learning
Java In-Depth: Become a Complete Java Engineer
Java Fundamentals: Collections
Data Structures in addition to Algorithms: Deep Dive Using Java
Algorithms in addition to Data Structures - Part 1 in addition to two
Data Structures inwards Java ix yesteryear Heinz Kabutz

No comments:

Post a Comment