Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator

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

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring