What is the LinkedHashMap.toString() method in Java?

A LinkedHashMap is the same as a HashMap, except that a LinkedHashMap maintains the insertion order, whereas a HashMap doesn’t. Internally, LinkedHashMap uses a doubly-linked list to maintain the insertion order.

The toString method returns the String representation of a LinkedHashMap object.

Syntax

public String toString()

Parameters

This method doesn’t take any parameters.

Return value

  • This method returns a String as a result.
  • The returned String contains all the entries in the order returned by the map’s entrySet method.
  • The returned String is enclosed by open and close braces {}.
  • Each entry of the map is separated by a comma ,.
  • Each entry is in the format of key = value.
  • The key and value are converted to String with the String.valueOf method.

Code

import java.util.LinkedHashMap;
class ToString {
public static void main( String args[] ) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "one");
map.put(2, "two");
System.out.println(map.toString());
}
}

Explanation

In the code above:

  • Line 1: We import the java.util.LinkedHashMap library.

  • Line 5: We create a LinkedHashMap with the name map.

  • Lines 6–7: We add two entries to the map.

  • Line 8: We use the toString() method to get the String representation of the map and print it.

Free Resources