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
Stringas a result. - The returned
Stringcontains all the entries in the order returned by the map’sentrySetmethod. - The returned
Stringis enclosed by open and close braces{}. - Each entry of the
mapis separated by a comma,. - Each entry is in the format of
key = value. - The
keyandvalueare converted toStringwith theString.valueOfmethod.
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.LinkedHashMaplibrary. -
Line 5: We create a
LinkedHashMapwith the namemap. -
Lines 6–7: We add two entries to the
map. -
Line 8: We use the
toString()method to get theStringrepresentation of themapand print it.