Tags

Feb 22, 2012

How to Iterate Over a Map in Java

There are several ways of iterating over a Map in Java.
following techniques will work for any map implementation HashMap, TreeMap, LinkedHashMap, Hashtable etc.

Method #1: Iterating over entries using For-Each loop.
This is the most common method and is preferable in most cases.

Map map = new HashMap();
for (Map.Entry entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

Method #2: Iterating over keys or values using For-Each loop.
Map map = new HashMap();

//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}
This method gives slight performance advantage over entrySet iteration and is more clean.

Method #3: Iterating using Iterator.

Map map = new HashMap();
Iterator> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:

Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}
f you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.

Check if one string is a rotation of other string

Two string s1 and s2 how will you check if s1 is a rotated version of s2

For Example:
if s1=avs then the following are some of its rotated versions:
vsa
sav
vas
where as "vas" is not a rotated version.
algorithm checkRotation(string s1, string s2) 
  if( len(s1) != len(s2))
    return false
  if( substring(s2,concat(s1,s1))
    return true
  return false
end
In Java:
boolean isRotation(String s1,String s2) {
    return (s1.length() == s2.length()) && ((s1+s1).indexOf(s2) != -1);
}

Create a custom exception in Java

Following are the steps to create custom exception.

(1) create a custom exception class in Java;
(2) throw our custom Java exception;
(3) catch our custom exception; and
(4) look at the output from our custom exception when we print a stack trace.

To create a custom exception class, all you have to do is extend the Java Exception class, and create a simple constructor:
/**
 * My custom exception class.
 */
class CustomException extends Exception
{
  public CustomException(String message)
  {
    super(message);
  }
}

A method to throw our custom Java exception



here's a small example class with a method named getUser that will throw our custom exception (CustomException) if the method is given the value of zero as a parameter.

/**
 * Our test class to demonstrate our custom exception.
 */
class User
{
  public String getUser(int i) throws CustomException
  {
    if (i == 0)
    {
      // throw our custom exception
      throw new CustomException("zero ...");
    }
    else
    {
      return "user";
    }
  }
}

To test our custom Java exception. In our main method, we'll create a new instance of our User class, then call the getUser method with the value of zero, which makes that method throw our custom Java exception:

/**
 * A class to test (throw) the custom exception we've created.
 *
 */
public class CustomExceptionExample
{
  public static void main(String[] args)
  {
    // create a new User
    User user= new User();
    
    try
    {
      // intentionally throw our custom exception by
      // calling getUser with a zero
      String userStr= user.getUser(0);
    }
    catch (CustomException e)
    {
      // print the stack trace
      e.printStackTrace();
    }
  }
}

To create a JAR file in the Eclipse workbench:

1. In the Package Explorer, we can optionally pre-select one or more Java elements to export. These will be open the wizard page.

2. Either from the context menu or from the menu bar's File menu, select Export.

3. Expand the Java node in the wizard page and select JAR file. Click Next.

4. In the JAR File Specification page, select the resources that we want to export in the Select the resources to export field.

5. Select the appropriate checkbox to specify whether we want to Export generated class files and resources or Export Java source files and resources. Note: Selected resources are exported in both cases.

6. In the Select the export destination field, either type or click Browse to select a location for the JAR file.

7. Select or clear the Compress the contents of the JAR file checkbox.

8. Select or clear the Overwrite existing files without warning checkbox. If we clear this checkbox, then we will be prompted to confirm the replacement of each file that will be overwritten.

9. Note: The overwrite option is applied when writing the JAR file, the JAR description, and the manifest file.

10. Now we have two options:

11. Click Finish to create the JAR file immediately.

12. Click Next to use the JAR Packaging Options page to set advanced options, create a JAR description, or change the default manifest.

13. If we want to save the JAR file description, select the Save the description of this JAR in the workspace checkbox. A JAR file description can be used to regenerate a JAR file without using the wizard.

14. The compiler is able to generate CLASS files even when source contains errors. We have the option to exclude CLASS (but not source) files with compile errors. These files will be reported at the end, if reporting is enabled.

15. We can choose to exclude CLASS (but not source) files that have compile warnings. These files will be reported at the end.
Note: This option does not automatically exclude class files with compile errors.

16. We can choose to include the source folder path by selecting the Create source folder structure checkbox.

17. Select the Build projects if not built automatically checkbox if you want the export to perform a build before creating the JAR file.

18. Click Finish to create the JAR file immediately or Next if we want to change the default manifest.

19. If it is not already selected, click the Generate the manifest file button

20. We can now choose to save the manifest in the workbench. This will save the manifest for later use. Click Save the manifest in the workspace, then click Browse next to the Manifest file field to specify a path and file name for the manifest.

21. If we decided to save the manifest file in the previous step and you chose to save the JAR description on the previous wizard page, then you can choose to reuse it in the JAR description (by selecting the Reuse and save the manifest in the workspace checkbox). This means that the saved file will be used when the JAR file is recreated from the JAR description.This option is useful if you want to modify or replace the manifest file before recreating the JAR file from the description.

22. We can choose to seal the JAR and optionally exclude some packages from being sealed or specify a list with sealed packages. By default, nothing is sealed.

23. Click the Browse button next to the Main class field to specify the entry point for our applications.
Note: If our class is not in the list, then we forgot to select it at the beginning. Click Finish. This will create the JAR, and optionally a JAR description and a manifest file.

Standard Naming Conventions in Java

There are a set of standard conventions which should be followed.


Class Naming
1) The class and interface names should start with Capital letters. A few examples of good class names is:
Car
Customer

Package Naming
2) The naming convention for package names says that they should start from the reverse of the domain name of your company.
com.companyname.productName.util.StringUtil
com.mycompany.productName.controller.HomeeController

Do note that all characters in the package names are in small letters.

Variables Naming
3) The variables should have a naming convention of
a) The first letter should be small letter
b) Every word in the variable names should start with a capital letter

Method Naming
4) The method names Starting with small letter and every other word staring with Capital letter.e.g.
checkUser()
addUser()

Constants Naming
5) The constants which are declared as public static final in Java should have all letters as capital and the words within the constant should be separated by _(underscore) character as:
DATE_PATTERN

Note: Same naming conventions should be used across the Java application.