Wednesday, April 3, 2013

Java - HashMap example and iterating through HashMap

Here is example of HashMap.

Now we will put some objects to the HashMap.
First we will create new Car class.
After that you can see how to add some object to these collection in line #39.
In line #46 we are checking if there is key "two" in our HashMap.
In line #49 we are checking if there is value "four" in HashMap.
In line #52 we are checking how much keys there is in our HashMap.
In line #54 you can see how get Object from HashMap by key.
In line #59 we are removing Object by key.

In lines #62 and #68 there is iterating through HashMap by key and
in line #74 there is iterating by value.

package p_2013_04_03;

import java.util.HashMap;
import java.util.Map;

class Car
{
 private String brand;
 private int year;
 
 public Car( String aBrand, int aYear )
 {
  this.brand = aBrand;
  this.year = aYear;
 }
 
 public void showBrand()
 {
  System.out.println( this.brand );
 }
 
 public void showYear()
 {
  System.out.println( this.year );
 }
}

public class MyHashMap 
{
 public static void main(String[] args) 
 {
  HashMap hm = new HashMap();
  
  Car opel = new Car("Opel", 2009);
  Car ford = new Car("Ford", 2007);
  Car bmw = new Car("BMW", 2011);
  Car mercedes = new Car("Mercedes", 2011);
  
  // put new value to the Map
  hm.put("one", opel);
  hm.put("two", ford);
  hm.put("three", bmw);
  hm.put("four", mercedes);
  
  // check if Map contains key: true or false
  System.out.println( hm.containsKey("two") );
  
  // check if Map contains value: true or false
  System.out.println( hm.containsKey("four") );
  
  // return the number of keys
  System.out.println( hm.size() );  
  
  // get object from the Map by key 
  Car carFromThree = hm.get("three");
  carFromThree.showBrand();
  
  // remove object from Map
  hm.remove("three");  
  
  // Iterate through Map - by key
  for(Map.Entry entry : hm.entrySet())
  {
   System.out.println( "Key: " + entry.getKey() + " | Value : " + entry.getValue() );
  }
  
  // Iterate through Map - by key
  for(String key : hm.keySet())
  {
   System.out.println( "Key: " + key );
  }
  
  // Iterate through Map - by value
  for(Car car : hm.values())
  {
   System.out.print( "Value: " );
   car.showBrand();
  }
 }
}

No comments: