keySet() vs entrySet vs values() Example inwards Java Map

The java.util.Map interface provides iii methods keySet(), entrySet() in addition to values() to retrieve all keys, entries (a key-value pair), in addition to values. Since these methods conduct come upwards from the Map interface, y'all tin displace role it amongst whatever of the Map implementation shape e.g. HashMap, TreeMap, LinkedHashMap, Hashtable, ConcurrentHashMap, and fifty-fifty amongst specialized Map implementations similar EnumMap, WeakHashMapand IdentityHashMap. In social club to choke a skilful Java developer, it's of import to empathise in addition to recall cardinal classes Java API e.g. Java's Collection framework. In this article, nosotros volition non solely acquire the difference betwixt keySet(), entrySet() in addition to values() methods, but too acquire how to role them inward Java plan past times looking at a uncomplicated example.


The keySet() method

This method returns a Set sentiment of all the keys inward the map. The prepare is backed past times the map, then changes to the map are reflected inward the set, in addition to vice-versa. If the map is modified piece an iteration over the Set is inward progress (except through the iterator's ain take away operation), the results of the iteration are undefined.

The prepare supports chemical component subdivision removal, which removes the corresponding mapping from the map, via the Iterator.remove(), Set.remove(), removeAll(), retainAll(), in addition to clear() operations, but It does non back upwards the add() or addAll() operations.


You tin displace too role the keySet() method to iterate over a Java HashMap equally shown inward 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 sentiment of the mappings contained inward this map. The prepare is backed past times the map, then changes to the map are reflected inward the set, in addition to vice-versa.

If the map is modified piece an iteration over the prepare is inward progress (except through the iterator's ain take away operation, or through the setValue() functioning on a map entry returned past times the iterator) the results of the iteration are undefined.

The Set too supports chemical component subdivision 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 upwards the add() or addAll() operations.

You tin displace too read Core Java for the Impatient past times Cay S. Horstmann to acquire virtually dissimilar views of Collection inward Java. One of the best books to acquire Java programming at the moment. It too covers Java SE 8.

 Since these methods conduct come upwards from the Map interface keySet() vs entrySet vs values() Example inward Java Map



Here is an instance of how y'all tin displace traverse over a Map inward Java using the entrySet() method. This is past times far the most efficient means 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 cardinal = 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 sentiment of the values contained inward this map. The collection is backed past times the map, then changes to the map are reflected inward the collection, in addition to vice-versa.

If the map is modified piece an iteration over the collection is inward progress (except through the iterator's ain take away operation), the results of the iteration are undefined. The collection supports chemical component subdivision 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 upwards the add() or addAll() operations.

Here is how y'all tin displace acquire all the values from a Map inward Java:

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

Here is dainty slid of summarizing dissimilar views of Map interface inward Java:

 Since these methods conduct come upwards from the Map interface keySet() vs entrySet vs values() Example inward Java Map


How to role keySet(), entrySet(), in addition to values() inward Java

Here is our sample Java plan to present y'all how y'all tin displace role the keySet(), entrySet() in addition to values() inward y'all Java Program. I accept only shown how y'all retrieve the respective view. I acquire out it to y'all what y'all desire to exercise amongst those sets. For example, y'all tin displace iterate over the Set to impress the mapping, or take away whatever specific mapping depending upon unopen to draw concern 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: cost 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 virtually keySet() vs entrySet() vs values() method inward Java. You accept learned how y'all tin displace obtain a dissimilar sentiment from your Map inward Java. This technique is applicable to all Map implementation including HashMap in addition to ConcurrentHashMap. You tin displace role these methods to iterate over Map equally good equally for removing entries from Map inward Java.

Btw, y'all should hold upwards mindful that these methods render collections that tin displace hold upwards modified automatically when the underlying collection changes. This tin displace exercise thread-safety issues inward concurrent Java programs. You tin displace farther read Core Java Volume 1 - Fundamentals past times Cay S. Horstmann to acquire virtually this sophisticated technique of providing sentiment instead of creating split Map classes. 

Further Learning
Java Fundamentals: Collections
From Collections to Streams inward Java 8 Using Lambda Expressions
What's New inward Java 8
Grokking Algorithms past times Aditya Bhargava
Java Programming Interview Exposed past times Makham

Subscribe to receive free email updates:

0 Response to "keySet() vs entrySet vs values() Example inwards Java Map"

Posting Komentar