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.
public String toString()
This method doesn’t take any parameters.
String
as a result.String
contains all the entries in the order returned by the map’s entrySet
method.String
is enclosed by open and close braces {}
.map
is separated by a comma ,
.key = value
.key
and value
are converted to String
with the String.valueOf
method.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());}}
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.