Skip to content

Java Print LinkedHashMap Example

This example shows how to print LinkedHashMap elements in Java. This example also shows how to print all keys, all values, and all mappings of LinkedHashMap using various ways.

How to print LinkedHashMap in Java?

The simplest way to print LinkedHashMap is by using the System.out.println method directly which uses the toString method of the LinkedHashMap class. The toString method, which is inherited from the AbstractMap class, returns a string representation of all mappings of the map enclosed by { and } and each key-value pair separated by a comma.

The order of the entries is determined by the iterator of the entry set.

Output

How to print all keys of the LinkedHashMap?

To print all keys of the LinkedHashMap, use the keySet method to get all the keys of the map.

Output

If you want to change the output format, you can also iterate the keys and print them one by one.

Output

How to print all keys of the LinkedHashMap?

To print all values of the LinkedHashMap object, use the values method which returns a Collection containing all the values contained in the LinkedHashMap object.

Output

Again, if you want to change the output format, you can iterate through the values of the LinkedHashMap and print them one by one.

Output

How to print all mappings of the LinkedHashMap?

To print all mappings of the LinkedHashMap, use the entrySet method which returns all the entries contained in the LinkedHashMap object.

Output

How to print LinkedHashMap containing custom class objects?

If the LinkedHashMap contains objects of a custom class as keys or values, then the custom class should implement the toString method for the output to be in human-readable format.

If the custom class does not override the toString method, the toString method of the Object class is used which prints the class name, followed by @, followed by hash code of the object as given below.

Output

As you can see from the output, the printed information is not very useful. Now, let’s override the toString method and try again.

Output

Tip: Always override the toString method in your custom classes.

This example is a part of the Java LinkedHashMap tutorial with examples.

Please let me know your views in the comments section below.

References:
Java 8 LinkedHashMap

About the author

Leave a Reply

Your email address will not be published.