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
package Examples;

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

public class MapEx {
	public static void main(String[] args) {
		// keys are Integers
		// Values are of type String
		Map<Integer, String> map = new HashMap<>();

		//add values in the map with a unique key 
		map.put(2, "C#");
        map.put(3, "Java");
        map.put(4, "JavaScript");
        map.put(5, "C++");
		
        // write to command line
		map.forEach((key, val) -> System.out.printf("%s %s%n", key, val));

		// add and remove from the map
		map.put(1, "PHP");
		map.put(6, "Jquery");
		map.remove(1);

		// write again to command line
		map.forEach((key, val) -> System.out.printf("%s %s%n", key, val));

	}
}

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

package Examples;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapEx {
	public static void main(String[] args) {
		// keys are Integers
		// Values are of type String
		Map<Integer, String> map = new HashMap<>();

		//add values in the map with a unique key 
		map.put(2, "C#");
        map.put(3, "Java");
        map.put(4, "JavaScript");
        map.put(5, "C++");
		
        // write to command line
		map.forEach((key, val) -> System.out.printf("%s %s%n", key, val));

		// add and remove from the map
		map.put(1, "PHP");
		map.put(6, "Jquery");
		map.remove(1);

		// write again to command line
		map.forEach((key, val) -> System.out.printf("%s %s%n", key, val));
		
		//Convert Map keys to array
		Integer[] keys = map.keySet().toArray(new Integer[map.keySet().size()]);
		 for (Integer vals : keys) {
	            System.out.println(vals);
	     }
		
		//Convert Map keys to an ArrayList
		List list = new ArrayList(map.keySet());
		 for (Integer vals : list) {
	            System.out.println(vals);
	     }

	}
}

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.

package Examples;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapEx {
	public static void main(String[] args) {
		// keys are Integers
		// Values are of type String
		Map<Integer, String> map = new HashMap<>();

		//add values in the map with a unique key 
		map.put(2, "C#");
        map.put(3, "Java");
        map.put(4, "JavaScript");
        map.put(5, "C++");
		
        // write to command line
		map.forEach((key, val) -> System.out.printf("%s %s%n", key, val));

		// add and remove from the map
		map.put(1, "PHP");
		map.put(6, "Jquery");
		map.remove(1);

		// write again to command line
		map.forEach((key, val) -> System.out.printf("%s %s%n", key, val));
		
		
		//use getOrDefault method
        map.put(10, map.getOrDefault(1, "PHP"));

		//Convert Map keys to array
		Integer[] keys = map.keySet().toArray(new Integer[map.keySet().size()]);
		
        // write to command line using lambda expression
        map.forEach((key, value) -> System.out.printf("%s %s%n", key, value));
		
		//Convert Map keys to an ArrayList
		List list = new ArrayList(map.keySet());
		 for (Integer vals : list) {
	            System.out.println(vals);
	     }

	}
}

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

 Integer calculatedVaue = map.computeIfAbsent("A", it -> 0);
        System.out.println(calculatedVaue);

No Responses

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.