How to Create a Map in Java

The Map interface in the Java API provides users with an easy way store information in so that it can be accessed based on its relationship to other information. There are a total of nineteen implementations of the Map interface in the Java 6.0 API, each suited to a specific task. The most general of the implementations is the HashMap class, and it is well suited to most needs for the Map interface.

Things You'll Need

  • Java

Instructions

    • 1

      Create a Java file named MapExample.java. Paste the following basic code into it:

      import java.util.Collection
      GO
      import java.util.HashMap
      GO

      /**

      • This class will provide an example for the MapInterface.
      • @author Kevin Walker
        */
        public class MapExample {
        /*
        This constructor method will perform some operations with the HashMap implementation
        of the Java Map interface as soon as created..
        /
        public MapExample() {
        }

      /*
      The main function will start up the MapExample constructor and nothing else.
      */

      public static void main(String[] args) {
      new MapExample()

      GO

      }

      }

    • 2

      Create a HashMap. Add the following line to the MapExample() constructor method:

          Map map = new HashMap()

      GO

      All implementations of the \"Map\" interface of the Java API relate data to a \"key\" represented by another piece of data. Since Map is an interface, you can't create a map directly, but should instead use one of the implementations provided by Java API. In this case, the simplest map, the HashMap, is used.

    • 3

      Populate the Hashmap. Add the next few lines of code to the same method as before:

          map.put(\"age\", 29)

      GO

          map.put(\"height\", 6.0)

      GO

          map.put(\"firstName\", \"Kevin\")

      GO

          map.put(\"lastName\", \"Walker\")

      GO

      As you can see, bits of information, called values, are being stored according to a keyword, called the key. Later, you will be able to retrieve the information knowing only the key. Its important to remember that when storing information in a Map, the key always comes first, and the value always comes second.

    • 4

      Retrieve information from the Map.

          System.out.println(\"First Name: \" + map.get(\"firstName\"))

      GO

          System.out.println(\"Last Name: \" + map.get(\"lastName\"))

      GO

          System.out.println(\"Age: \" + map.get(\"age\") + \" years\")

      GO

          System.out.println(\"height: \" + map.get(\"height\") + \" feet\");
    • 5

      Build a limited Map. All implementations of the Map interface can be initialized to require certain types of data and not others. Add the following line to the same method:

          Map<String, Integer> limitedMap = new HashMap()

      GO

      In this example, a Map is being initialized that requires a String for a key and relates it to an Integer of data. So, out of the code:

          limitedMap.put(\"age\", 29)

      GO

          limitedMap.put(\"height\", 6.0)

      GO

          limitedMap.put(\"firstName\", \"Kevin\")

      GO

          limitedMap.put(\"lastName\", \"Walker\")

      GO

      Only the first line will work. Line two will cause a compiler error because it is attempting to store a double instead of an Integer. Lines three and four will cause a compiler error because they are attempting to store strings.

Tips & Warnings

  • Programmers familiar with the concept of arrays may think of Maps as arrays in which data is accessed by a relationship with other information instead of by its position in the array. A common way of accessing data in a Map is a String keyword, but other relationships are possible.
  • Maps do not implement the Collection interface, and this means that you cannot use the \"for (Object x : Map m)\" syntax for iterating through them.
  • Many of the default implementations of the Map interface, including the Hashmap class, do not maintain the order of the items given. For collections of data that must remain sorted, consider the TreeMap class.
  • When creating maps that accept only limited values, primitives data types like \"int\" and \"double\" cannot be used either as keys or as values. Instead, you must use their class-based equivalents, \"Integer\" and \"Double.\"
Related Searches

References

  • Photo Credit dictionary image by Ben Higham from Fotolia.com

You May Also Like

Related Ads

View Blog Post

Enter the Geek Vs Geek Giveaway and Win a Roku!