Wednesday, 8 August 2012

How to get all keys in Java TreeMap?


This Java Example shows how to retrieve all keys contained in TreeMap using keySet method of Java TreeMap class.

import java.util.Set;
import java.util.TreeMap;

public class GetKeysFromTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap

  TreeMap phoneBook = new TreeMap();

  // Adding key value pairs to TreeMap

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * Set keySet() - Returns a set view of the keys
   * contained in this map in ascending order.
   **/

  Set nameSet = phoneBook.keySet();

  System.out.println("Names in the phone book are :");

  for (Object name : nameSet) {
   System.out.println("Name: " + name);
  }

 }
}


The output is:


Names in the phone book are :
Name: John
Name: Joy
Name: Roy

Tuesday, 7 August 2012

Get Set view of Keys from Java TreeMap example


This Java Example shows how to get a Set of keys contained in TreeMap using keySet method of Java TreeMap class.


import java.util.Set;
import java.util.TreeMap;

public class GetSetViewOfKeysFromTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap

  TreeMap phoneBook = new TreeMap();

  // Add key value pairs to TreeMap.

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  /**
   * Set keySet() - Returns a set view of the keys contained
   * in this map in ascending order.
   **/

  Set nameSet = phoneBook.keySet();

  System.out.println("Names in the phone book are :");

  for (Object name : nameSet) {
   System.out.println("Name: " + name);
  }

  /**
   * Please note that resultant Set object is backed by
   * the TreeMap. Any key that is removed from Set will
   * also be removed from original TreeMap object. The same
   * is not the case with the element addition.
   **/

  // remove Roy from nameSet

  nameSet.remove("Roy");

  // check if original TreeMap still contains entry for name Roy.
  boolean blnExists = phoneBook.containsKey("Roy");
  System.out.println("Does TreeMap contain Roy ? " + blnExists);
 }
}


The output is:


Names in the phone book are :
Name: John
Name: Joy
Name: Roy
Does TreeMap contain Roy ? false

Iterate through the values of Java TreeMap example


This Java Example shows how to iterate through the values contained in the TreeMap object.


import java.util.Collection;
import java.util.TreeMap;
import java.util.Iterator;

public class IterateValuesOfTreeMapExample {

 public static void main(String[] args) {

  // create TreeMap object
  TreeMap tMap = new TreeMap();

  // add key value pairs to TreeMap
  tMap.put("1", "One");
  tMap.put("2", "Two");
  tMap.put("3", "Three");

  /**
    values() - Returns a collection view of the values contained
     in this map. The collection's iterator will return the values
     in the order that their corresponding keys appear in the tree.
     The collection is backed by this TreeMap instance, so changes
     to this map are reflected in the collection, and vice-versa
   **/
  Collection c = tMap.values();

  // obtain an Iterator for Collection
  Iterator itr = c.iterator();

  System.out.println("The map contains values...");
  // iterate through TreeMap values iterator
  while (itr.hasNext())
   System.out.println(itr.next());
 }
}


The output is:


The map contains values...
One
Two
Three

Simple Java TreeMap example


This simple Java Example shows how to use Java TreeMap. It also describes how to add something to  TreeMap and how to retrieve the value added from  TreeMap .



import java.util.Set;
import java.util.TreeMap;

public class JavaTreeMapExample {

 public static void main(String[] args) {

  // create object of TreeMap
  TreeMap phoneBook = new TreeMap();

  /**
   * Add key value pair to TreeMap using Object put(Object key, Object
   * value) method of Java TreeMap class, where key and value both are
   * objects put method returns Object which is either the value
   * previously tied to the key or null if no value mapped to the key.
   **/

  phoneBook.put("John", "245745");
  phoneBook.put("Joy", "245786");
  phoneBook.put("Roy", "233783");

  // retrieve value using Object get(Object key) method of Java TreeMap
  // class
  Object phoneNo = phoneBook.get("Joy");
  System.out.println("Phone number of Joy: " + phoneNo);

  System.out.println("The Map contains...");

  /**
   * Set keySet() - Returns a Set view of the keys contained in this map.
   * The set's iterator will return the keys in ascending order. The map
   * is backed by this TreeMap instance, so changes to this map are
   * reflected in the Set, and vice-versa.
   **/

  Set nameSet = phoneBook.keySet();
  for (Object name : nameSet) {
   System.out.println("Name: " + name + " Phone: "
     + phoneBook.get(name));
  }

  /**
   * put - If the map previously contained a mapping for this key, the old
   * value is replaced and the put method returns the old value.
   **/

  Object oldPhone = phoneBook.put("Roy", "222222");

  System.out.println("Roy's old phone number:" + oldPhone);
  System.out.println("Roy's new phone number:" + phoneBook.get("Roy"));

 }
}


The output is:


Phone number of Joy: 245786
The Map contains...
Name: John Phone: 245745
Name: Joy Phone: 245786
Name: Roy Phone: 233783
Roy's old phone number:233783
Roy's new phone number:222222

Monday, 6 August 2012

Checked vs Unchecked Exceptions in Java

Type of exceptions in java are checked exceptions and unchecked exceptions. This classification is based on compile-time checking of exceptions.

At compile time, the java compiler checks that a program contains handlers for checked exceptions.Either you have to enclose the code with a try-catch block or the method must declares that a method can throw a given exception using 'throws' clause, and the caller to that method must explicitly handle the exception (or 'throw it up' to the next caller up the chain).

The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes. Because the compiler doesn’t forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.

Unchecked exceptions behave as follows:



  • They they don't have to be explicitly caught. When an unchecked exception occurs, such as a NullPointerException, ClassCastException,OutOfMemoryError etc, Java will "handle" the exception automatically (see below).

  • Methods and constructors don't have to explicitly state that they can throw an unchecked exception. It's taken for granted that any method can throw them.

  • Indeed, certain Java bytecode instructions (such as array access, invoking a method on an object, integer division etc) can actually throw an unchecked exception.