Java How to Read Keys in Map

Java HashMap Tutorial with Examples

Java HashMap is a hash table based implementation of Coffee's Map interface. A Map, as you lot might know, is a collection of central-value pairs. It maps keys to values.

Java HashMap in Collection Hierarchy

Following are few key points to notation nigh HashMaps in Java -

  • A HashMap cannot contain indistinguishable keys.

  • Java HashMap allows null values and the null key.

  • HashMap is an unordered drove. Information technology does non guarantee any specific order of the elements.

  • Java HashMap is not thread-prophylactic. You must explicitly synchronize concurrent modifications to the HashMap.

Creating a HashMap and Adding key-value pairs to information technology

The following case shows how to create a HashMap, and add new central-value pairs to it.

                                  import                  java.util.                                    HashMap                  ;                  import                  coffee.util.                                    Map                  ;                  public                  class                  CreateHashMapExample                  {                  public                  static                  void                  main                  (                  String                  [                  ]                  args)                  {                  // Creating a HashMap                  Map                                      <                    String                    ,                    Integer                    >                                    numberMapping                  =                  new                  HashMap                                      <                    >                                    (                  )                  ;                  // Adding key-value pairs to a HashMap                  numberMapping.                  put                  (                  "One"                  ,                  one                  )                  ;                  numberMapping.                  put                  (                  "Two"                  ,                  2                  )                  ;                  numberMapping.                  put                  (                  "Three"                  ,                  3                  )                  ;                  // Add a new key-value pair simply if the key does not exist in the HashMap, or is mapped to `null`                  numberMapping.                  putIfAbsent                  (                  "4"                  ,                  iv                  )                  ;                  Organization                  .out.                  println                  (numberMapping)                  ;                  }                  }                              
                # Output {Ane=ane, 4=4, Two=2, Iii=3}              

Accessing keys and modifying their associated value in a HashMap

The example beneath shows:

  • How to cheque if a HashMap is empty | isEmpty()
  • How to find the size of a HashMap | size()
  • How to cheque if a given key exists in a HashMap | containsKey()
  • How to bank check if a given value exists in a HashMap | containsValue()
  • How to get the value associated with a given central in the HashMap | get()
  • How to change the value associated with a given key in the HashMap | put()
                                  import                  java.util.                                    HashMap                  ;                  import                  java.util.                                    Map                  ;                  public                  class                  AccessKeysFromHashMapExample                  {                  public                  static                  void                  principal                  (                  String                  [                  ]                  args)                  {                  Map                                      <                    String                    ,                    Cord                    >                                    userCityMapping                  =                  new                  HashMap                                      <                    >                                    (                  )                  ;                  // Cheque if a HashMap is empty                  System                  .out.                  println                  (                  "is userCityMapping empty? : "                  +                  userCityMapping.                  isEmpty                  (                  )                  )                  ;                  userCityMapping.                  put                  (                  "John"                  ,                  "New York"                  )                  ;                  userCityMapping.                  put                  (                  "Rajeev"                  ,                  "Bengaluru"                  )                  ;                  userCityMapping.                  put                  (                  "Steve"                  ,                  "London"                  )                  ;                  System                  .out.                  println                  (                  "userCityMapping HashMap : "                  +                  userCityMapping)                  ;                  // Find the size of a HashMap                  System                  .out.                  println                  (                  "Nosotros have the city information of "                  +                  userCityMapping.                  size                  (                  )                  +                  " users"                  )                  ;                  String                  userName                  =                  "Steve"                  ;                  // Bank check if a key exists in the HashMap                  if                  (userCityMapping.                  containsKey                  (userName)                  )                  {                  // Become the value assigned to a given central in the HashMap                  String                  city                  =                  userCityMapping.                  become                  (userName)                  ;                  System                  .out.                  println                  (userName                  +                  " lives in "                  +                  city)                  ;                  }                  else                  {                  System                  .out.                  println                  (                  "City details not found for user "                  +                  userName)                  ;                  }                  // Cheque if a value exists in a HashMap                  if                  (userCityMapping.                  containsValue                  (                  "New York"                  )                  )                  {                  Arrangement                  .out.                  println                  (                  "There is a user in the userCityMapping who lives in New York"                  )                  ;                  }                  else                  {                  Arrangement                  .out.                  println                  (                  "There is no user in the userCityMapping who lives in New York"                  )                  ;                  }                  // Modify the value assigned to an existing fundamental                  userCityMapping.                  put                  (userName,                  "California"                  )                  ;                  System                  .out.                  println                  (userName                  +                  " moved to a new metropolis "                  +                  userCityMapping.                  get                  (userName)                  +                  ", New userCityMapping : "                  +                  userCityMapping)                  ;                  // The get() method returns `goose egg` if the specified central was not found in the HashMap                  System                  .out.                  println                  (                  "Lisa'southward city : "                  +                  userCityMapping.                  get                  (                  "Lisa"                  )                  )                  ;                  }                  }                              
                                  # Output                  is userCityMapping empty?                  :                  true                  userCityMapping HashMap                  :                  {Steve=London,                  John                  =New York,                  Rajeev                  =Bengaluru}                  Nosotros accept the urban center information of                  iii                  users                  Steve lives                  in                  London There is a user                  in                  the userCityMapping                  who                  lives                  in                  New York Steve moved to a new city California, New userCityMapping                  :                  {Steve=California,                  John                  =New York,                  Rajeev                  =Bengaluru}                  Lisa'south urban center                  :                  null              

Removing keys from a HashMap

The following example shows how to :

  • Remove a fundamental from a HashMap | remove(Object central)
  • Remove a key from a HashMap merely if information technology is associated with a given value | remove(Object cardinal, Object value)
                                  import                  java.util.                                    HashMap                  ;                  import                  coffee.util.                                    Map                  ;                  public                  grade                  RemoveKeysFromHashMapExample                  {                  public                  static                  void                  main                  (                  Cord                  [                  ]                  args)                  {                  Map                                      <                    String                    ,                    String                    >                                    husbandWifeMapping                  =                  new                  HashMap                                      <                    >                                    (                  )                  ;                  husbandWifeMapping.                  put                  (                  "Jack"                  ,                  "Marie"                  )                  ;                  husbandWifeMapping.                  put                  (                  "Chris"                  ,                  "Lisa"                  )                  ;                  husbandWifeMapping.                  put                  (                  "Steve"                  ,                  "Jennifer"                  )                  ;                  Organization                  .out.                  println                  (                  "Husband-Married woman Mapping : "                  +                  husbandWifeMapping)                  ;                  // Remove a key from the HashMap                  // Ex - Unfortunately, Chris got divorced. Let's remove him from the mapping                  String                  husband                  =                  "Chris"                  ;                  String                  married woman                  =                  husbandWifeMapping.                  remove                  (hubby)                  ;                  System                  .out.                  println                  (                  "Couple ("                  +                  hubby                  +                  " => "                  +                  married woman                  +                  ") got divorced"                  )                  ;                  Organisation                  .out.                  println                  (                  "New Mapping : "                  +                  husbandWifeMapping)                  ;                  // Remove a primal from the HashMap but if it is mapped to the given value                  // Ex - Divorce "Jack" only if He is married to "Linda"                  boolean                  isRemoved                  =                  husbandWifeMapping.                  remove                  (                  "Jack"                  ,                  "Linda"                  )                  ;                  System                  .out.                  println                  (                  "Did Jack get removed from the mapping? : "                  +                  isRemoved)                  ;                  // remove() returns null if the mapping was non found for the supplied cardinal                  wife                  =                  husbandWifeMapping.                  remove                  (                  "David"                  )                  ;                  if                  (wife                  ==                  cypher                  )                  {                  System                  .out.                  println                  (                  "Looks like David is non married to anyone"                  )                  ;                  }                  else                  {                  Arrangement                  .out.                  println                  (                  "Removed David and his married woman from the mapping"                  )                  ;                  }                  }                  }                              
                                  # Output                  Husband-Married woman Mapping                  :                  {Steve=Jennifer,                  Chris                  =Lisa,                  Jack                  =Marie}                  Couple                  (Chris                  =                  >                  Lisa)                  got divorced New Mapping                  :                  {Steve=Jennifer,                  Jack                  =Marie}                  Did Jack go removed from the mapping?                  :                  false                  Looks like David is non married to anyone              

Obtaining the entrySet, keySet, and values from a HashMap

The Map interface provides methods to retrieve the ready of entries (cardinal-value pairs), the set of keys, and the drove of values.

The following example shows how to call back them from a HashMap -

                                  import                  java.util.                                    Collection                  ;                  import                  coffee.util.                                    HashMap                  ;                  import                  java.util.                                    Map                  ;                  import                  java.util.                                    Prepare                  ;                  public                  class                  HashMapEntryKeySetValuesExample                  {                  public                  static                  void                  principal                  (                  String                  [                  ]                  args)                  {                  Map                                      <                    String                    ,                    String                    >                                    countryISOCodeMapping                  =                  new                  HashMap                                      <                    >                                    (                  )                  ;                  countryISOCodeMapping.                  put                  (                  "India"                  ,                  "IN"                  )                  ;                  countryISOCodeMapping.                  put                  (                  "U.s.a. of America"                  ,                  "U.s."                  )                  ;                  countryISOCodeMapping.                  put                  (                  "Russia"                  ,                  "RU"                  )                  ;                  countryISOCodeMapping.                  put                  (                  "Japan"                  ,                  "JP"                  )                  ;                  countryISOCodeMapping.                  put                  (                  "China"                  ,                  "CN"                  )                  ;                  // HashMap's entry prepare                  Set                                      <                    Map.Entry                    <                    String                    ,                    String                    >                    >                                    countryISOCodeEntries                  =                  countryISOCodeMapping.                  entrySet                  (                  )                  ;                  Organization                  .out.                  println                  (                  "countryISOCode entries : "                  +                  countryISOCodeEntries)                  ;                  // HashMap'due south key set up                  Prepare                                      <                    Cord                    >                                    countries                  =                  countryISOCodeMapping.                  keySet                  (                  )                  ;                  Organization                  .out.                  println                  (                  "countries : "                  +                  countries)                  ;                  // HashMap'south values                  Collection                                      <                    String                    >                                    isoCodes                  =                  countryISOCodeMapping.                  values                  (                  )                  ;                  System                  .out.                  println                  (                  "isoCodes : "                  +                  isoCodes)                  ;                  }                  }                              
                                  # Output                  countryISOCode entries                  :                  [U.s. of                  America                  =U.s.a.,                  Nippon                  =JP,                  China                  =CN,                  India                  =IN,                  Russia                  =RU]                  countries                  :                  [United states of America, Japan, Communist china, India, Russian federation]                  isoCodes                  :                  [Us, JP, CN, IN, RU]                              

Iterating over a HashMap

The following example shows different ways of iterating over a HashMap -

  1. Iterating over a HashMap using Java 8 forEach and lambda expression.

  2. Iterating over the HashMap's entrySet using iterator().

  3. Iterating over the HashMap's entrySet using Java viii forEach and lambda expression.

  4. Iterating over the HashMap's entrySet using simple for-each loop.

  5. Iterating over the HashMap'southward keySet.

                                  import                  java.util.                                    HashMap                  ;                  import                  java.util.                                    Iterator                  ;                  import                  java.util.                                    Map                  ;                  import                  coffee.util.                                    Set                  ;                  public                  class                  IterateOverHashMap                  {                  public                  static                  void                  main                  (                  String                  [                  ]                  args)                  {                  Map                                      <                    String                    ,                    Double                    >                                    employeeSalary                  =                  new                  HashMap                                      <                    >                                    (                  )                  ;                  employeeSalary.                  put                  (                  "David"                  ,                  76000.00                  )                  ;                  employeeSalary.                  put                  (                  "John"                  ,                  120000.00                  )                  ;                  employeeSalary.                  put                  (                  "Marking"                  ,                  95000.00                  )                  ;                  employeeSalary.                  put                  (                  "Steven"                  ,                  134000.00                  )                  ;                  System                  .out.                  println                  (                  "=== Iterating over a HashMap using Java eight forEach and lambda ==="                  )                  ;                  employeeSalary.                  forEach                  (                  (employee,                  bacon)                  ->                  {                  System                  .out.                  println                  (employee                  +                  " => "                  +                  salary)                  ;                  }                  )                  ;                  System                  .out.                  println                  (                  "\n=== Iterating over the HashMap's entrySet using iterator() ==="                  )                  ;                  Fix                                      <                    Map.Entry                    <                    String                    ,                    Double                    >                    >                                    employeeSalaryEntries                  =                  employeeSalary.                  entrySet                  (                  )                  ;                  Iterator                                      <                    Map.Entry                    <                    String                    ,                    Double                    >                    >                                    employeeSalaryIterator                  =                  employeeSalaryEntries.                  iterator                  (                  )                  ;                  while                  (employeeSalaryIterator.                  hasNext                  (                  )                  )                  {                  Map.Entry                                      <                    String                    ,                    Double                    >                                    entry                  =                  employeeSalaryIterator.                  next                  (                  )                  ;                  Arrangement                  .out.                  println                  (entry.                  getKey                  (                  )                  +                  " => "                  +                  entry.                  getValue                  (                  )                  )                  ;                  }                  System                  .out.                  println                  (                  "\n=== Iterating over the HashMap'southward entrySet using Java 8 forEach and lambda ==="                  )                  ;                  employeeSalary.                  entrySet                  (                  )                  .                  forEach                  (entry                  ->                  {                  Arrangement                  .out.                  println                  (entry.                  getKey                  (                  )                  +                  " => "                  +                  entry.                  getValue                  (                  )                  )                  ;                  }                  )                  ;                  Organization                  .out.                  println                  (                  "\n=== Iterating over the HashMap's entrySet using uncomplicated for-each loop ==="                  )                  ;                  for                  (                  Map.Entry                                      <                    String                    ,                    Double                    >                                    entry:                  employeeSalary.                  entrySet                  (                  )                  )                  {                  System                  .out.                  println                  (entry.                  getKey                  (                  )                  +                  " => "                  +                  entry.                  getValue                  (                  )                  )                  ;                  }                  Organisation                  .out.                  println                  (                  "\n=== Iterating over the HashMap's keySet ==="                  )                  ;                  employeeSalary.                  keySet                  (                  )                  .                  forEach                  (employee                  ->                  {                  Arrangement                  .out.                  println                  (employee                  +                  " => "                  +                  employeeSalary.                  become                  (employee)                  )                  ;                  }                  )                  ;                  }                  }                              
                # Output === Iterating over a HashMap using Java 8 forEach and lambda === David => 76000.0 John => 120000.0 Mark => 95000.0 Steven => 134000.0  === Iterating over the HashMap'southward entrySet using iterator() === David => 76000.0 John => 120000.0 Mark => 95000.0 Steven => 134000.0  === Iterating over the HashMap's entrySet using Java viii forEach and lambda === David => 76000.0 John => 120000.0 Mark => 95000.0 Steven => 134000.0  === Iterating over the HashMap'due south entrySet using unproblematic for-each loop === David => 76000.0 John => 120000.0 Mark => 95000.0 Steven => 134000.0  === Iterating over the HashMap'southward keySet === David => 76000.0 John => 120000.0 Mark => 95000.0 Steven => 134000.0              

Java HashMap with User divers objects

Check out the post-obit instance to learn how to create and work with a HashMap of user defined objects.

                                  import                  coffee.util.                                    HashMap                  ;                  import                  java.util.                                    Map                  ;                  class                  Employee                  {                  private                  Integer                  id;                  private                  String                  name;                  private                  String                  city;                  public                  Employee                  (                  Integer                  id,                  String                  name,                  String                  metropolis)                  {                  this                  .id                  =                  id;                  this                  .name                  =                  proper noun;                  this                  .urban center                  =                  city;                  }                  public                  Integer                  getId                  (                  )                  {                  render                  id;                  }                  public                  void                  setId                  (                  Integer                  id)                  {                  this                  .id                  =                  id;                  }                  public                  String                  getName                  (                  )                  {                  return                  name;                  }                  public                  void                  setName                  (                  String                  name)                  {                  this                  .name                  =                  name;                  }                  public                  String                  getCity                  (                  )                  {                  render                  urban center;                  }                  public                  void                  setCity                  (                  String                  urban center)                  {                  this                  .city                  =                  city;                  }                  @Override                  public                  String                  toString                  (                  )                  {                  return                  "Employee{"                  +                  "proper noun='"                  +                  proper noun                  +                  '\''                  +                  ", urban center='"                  +                  city                  +                  '\''                  +                  '}'                  ;                  }                  }                  public                  course                  HashMapUserDefinedObjectExample                  {                  public                  static                  void                  main                  (                  Cord                  [                  ]                  args)                  {                  Map                                      <                    Integer                    ,                    Employee                    >                                    employeesMap                  =                  new                  HashMap                                      <                    >                                    (                  )                  ;                  employeesMap.                  put                  (                  1001                  ,                  new                  Employee                  (                  1001                  ,                  "Rajeev"                  ,                  "Bengaluru"                  )                  )                  ;                  employeesMap.                  put                  (                  1002                  ,                  new                  Employee                  (                  1002                  ,                  "David"                  ,                  "New York"                  )                  )                  ;                  employeesMap.                  put                  (                  1003                  ,                  new                  Employee                  (                  1003                  ,                  "Jack"                  ,                  "Paris"                  )                  )                  ;                  System                  .out.                  println                  (employeesMap)                  ;                  }                  }                              
                # Output {1001=Employee{name='Rajeev', city='Bengaluru'}, 1002=Employee{proper noun='David', urban center='New York'}, 1003=Employee{name='Jack', urban center='Paris'}}              

Synchronizing Admission to Java HashMap

Java HashMap is non thread-prophylactic. Information technology may become non-deterministic in multi-threaded environments where multiple threads try to modify the HashMap meantime.

Example demonstrating HashMap's unpredictable behavior in multi-threaded environments

The following case demonstrates how HashMap becomes non-deterministic when multiple threads try to change it at the aforementioned time -

                                  import                  coffee.util.                                    HashMap                  ;                  import                  java.util.                                    Map                  ;                  import                  coffee.util.concurrent.                                    ExecutorService                  ;                  import                  java.util.concurrent.                                    Executors                  ;                  import                  coffee.util.concurrent.                                    TimeUnit                  ;                  public                  form                  UnsafeHashMapExample                  {                  public                  static                  void                  master                  (                  Cord                  [                  ]                  args)                  throws                  InterruptedException                  {                  Map                                      <                    Cord                    ,                    Integer                    >                                    cricketTeamScore                  =                  new                  HashMap                                      <                    >                                    (                  )                  ;                  cricketTeamScore.                  put                  (                  "Australia"                  ,                  349                  )                  ;                  cricketTeamScore.                  put                  (                  "Republic of india"                  ,                  250                  )                  ;                  // Create an ExecutorService with a Thread Pool of size 10                  ExecutorService                  executorService                  =                  Executors                  .                  newFixedThreadPool                  (                  10                  )                  ;                  // Create a Runnable object that increments the value associated with a given key in the HashMap past i.                  Runnable                  task                  =                  (                  )                  ->                  {                  incrementTeamScore                  (cricketTeamScore,                  "India"                  )                  ;                  }                  ;                  // Submit the Runnable object to the executorService 100 times to examination concurrent modifications                  for                  (                  int                  i                  =                  0                  ;                  i                  <                  100                  ;                  i++                  )                  {                  executorService.                  submit                  (task)                  ;                  }                  executorService.                  shutdown                  (                  )                  ;                  executorService.                  awaitTermination                  (                  lx                  ,                  TimeUnit                  .SECONDS)                  ;                  Arrangement                  .out.                  println                  (                  "Final Score of Squad Bharat : "                  +                  cricketTeamScore.                  get                  (                  "India"                  )                  )                  ;                  }                  // Increase the score of a team past one                  private                  static                  void                  incrementTeamScore                  (                  Map                                      <                    String                    ,                    Integer                    >                                    cricketTeamScore,                  String                  team)                  {                  Integer                  score                  =                  cricketTeamScore.                  get                  (team)                  ;                  cricketTeamScore.                  put                  (squad,                  score                  +                  i                  )                  ;                  }                  }                              

The final output of the in a higher place plan should be 350 because the initial value was 250, and we're incrementing it 100 times.

But since multiple threads try to alter the HashMap concurrently, the change washed by one thread gets overridden past some other thread, and the output becomes non-deterministic.

If you run the to a higher place program multiple times, you lot'll find that it produces different output each time it is run.

                # Output Final Score of Team India : 343              

Yous can learn more most concurrency issues like this from my Java Concurrency Issues and Thread Synchronization tutorial.

Example demonstrating how to synchronize concurrent modifications to a HashMap

Let'southward write the thread-safe version of the previous programme. We can make the following two changes to the plan to make information technology thread-prophylactic -

  • Utilise the Collections.synchronizedMap() method to obtain a synchronized view of the HashMap.

  • Write the increment logic within a synchronized block.

                                  import                  java.util.                                    Collections                  ;                  import                  java.util.                                    HashMap                  ;                  import                  java.util.                                    Map                  ;                  import                  java.util.concurrent.                                    *                  ;                  public                  form                  SynchronizedHashMapExample                  {                  public                  static                  void                  chief                  (                  Cord                  [                  ]                  args)                  throws                  InterruptedException                  {                  Map                                      <                    Cord                    ,                    Integer                    >                                    cricketTeamScore                  =                  Collections                  .                  synchronizedMap                  (                  new                  HashMap                                      <                    >                                    (                  )                  )                  ;                  cricketTeamScore.                  put                  (                  "Australia"                  ,                  349                  )                  ;                  cricketTeamScore.                  put                  (                  "India"                  ,                  250                  )                  ;                  // Create an ExecutorService with a Thread Pool of size 10                  ExecutorService                  executorService                  =                  Executors                  .                  newFixedThreadPool                  (                  10                  )                  ;                  // Create a Runnable object that increments the value associated with a given key in the HashMap by one.                  Runnable                  task                  =                  (                  )                  ->                  {                  incrementTeamScore                  (cricketTeamScore,                  "Republic of india"                  )                  ;                  }                  ;                  // Submit the Runnable object to the executorService 100 times to test concurrent modifications                  for                  (                  int                  i                  =                  0                  ;                  i                  <                  100                  ;                  i++                  )                  {                  executorService.                  submit                  (task)                  ;                  }                  executorService.                  shutdown                  (                  )                  ;                  executorService.                  awaitTermination                  (                  threescore                  ,                  TimeUnit                  .SECONDS)                  ;                  System                  .out.                  println                  (                  "Concluding Score of Team India : "                  +                  cricketTeamScore.                  get                  (                  "India"                  )                  )                  ;                  }                  // Increase the score of a team by one                  private                  static                  void                  incrementTeamScore                  (                  Map                                      <                    String                    ,                    Integer                    >                                    cricketTeamScore,                  String                  team)                  {                  synchronized                  (cricketTeamScore)                  {                  Integer                  score                  =                  cricketTeamScore.                  go                  (squad)                  ;                  cricketTeamScore.                  put                  (team,                  score                  +                  1                  )                  ;                  }                  }                  }                              

This program produces the right output -

                                  # Output                  Terminal Score of Squad Republic of india                  :                  350                              

Y'all tin also use a ConcurrentHashMap for thread safety instead of the HashMap obtained via Collections.synchronizedMap() method. The ConcurrentHashMap provides thread-safe operations on the Map.

Conclusion

Congratulations folks! In this article, you learned what is a HashMap, how to create a HashMap, how to add together new key-value pairs to a HashMap, how to remove keys from a HashMap, how to iterate over a HashMap, and how to synchronize a HashMap.

As always, Thanks for reading. Encounter you lot in the next post.

tafoyacolize.blogspot.com

Source: https://www.callicoder.com/java-hashmap/

0 Response to "Java How to Read Keys in Map"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel