Map Interface in Java

Before proceeding with this article, If you are a new reader and you are not much familiar about collections. Read this article for more information ( Collections in java). Following are the key points to remember about Map and HashMap in java.

  1. Maps keys to values and can’t contain duplicate keys
  2. Each key map at least one value. There is a one to many relationship between keys and values
  3. HashMap is an efficient implementation of Map interface

One can convert May keys into arrays with the following code.

Alternatively one can use lambda expressions to retrieve values using foreach method.  Another method getOrDefault() is also available to retrieve the current value and if the value is not available it will return a default value. Following example demonstrates how to use lambda expression with foreach method and getOrDegault method. It is available in java 8 onward.

There is an additional method can be used to calculate a value if it is absent in current map.

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *