Java - LinkedHashMap example

Posted on October 24, 2016

LinkedHashMap is a hash table and linked list implementation of the Map interface.  The LinkedHashMap  class does not provide ordering as TreeMap but  it maintain the order of elements as they are inserted.

In the below example, we will show you various methods of LinkedHashMap class.

  • put() - add key and value into the Map.
  • get() - return value by passing key.
  • remove() - delete key and value  from the map.
  • size() - return size of map.
  • containsKey() - return true if key exist in map otherwise return false.
  • containsValue() - return true if value exist in map otherwise return false.
  • clear() - remove all elements from map

package com.boraji.tutorial;

import java.util.LinkedHashMap;
import java.util.Map;

 * @author imssbora
public class LinkedHashMapExample {
	public static void main(String[] args) {
		Map<String, String> map=new LinkedHashMap<>();
		/*Adding key and values in LinkedHashMap*/
		map.put("1", "One");
		map.put("2", "Two");
		map.put("4", "Four");
		map.put("5", "Five");
		System.out.println("LinkedHashMap key-values:"+map);
		/*Get value by key from the LinkedHashMap*/
		System.out.println("Value of '4' is: "+map.get("4"));
		/*Removing key and value from the LinkedHashMap	*/
		System.out.println("After removal, LinkedHashMap Key-Value: " +map);
		/*Getting size of LinkedHashMap*/
		System.out.println("Size of LinkedHashMap is : "+map.size());
		/*Checking if key exist in the LinkedHashMap or not*/
		System.out.println("Key '3' exist: "+map.containsKey("3"));
		/*Checking if value exist in the LinkedHashMap or not*/
		System.out.println("Key '6' exist: "+map.containsValue("6"));
		/*Remove all keys and values from the LinkedHashMap*/
		System.out.println("After clearing LinkedHashMap: "+map);


LinkedHashMap key-values:{1=One, 2=Two, 3=Three, 4=Four, 5=Five}
Value of '4' is: Four
After removal, LinkedHashMap Key-Value: {1=One, 2=Two, 3=Three, 5=Five}
Size of LinkedHashMap is : 4
Key '3' exist: true
Key '6' exist: false
After clearing LinkedHashMap: {}