Print HashMap in Java

Print HashMap in java

In this article, we will see how to print HashMap in java using different method.

Print from the HashMap Reference

This is the most basic and easiest method to print out HashMap in java. Pass the HashMap reference to the System.out.println, and the HashMap will output the key-value of the elements enclosed in curly brackets.

We will use a HashMap constructor and a pass Map of elements to the constructor, which provides an easier way to initialize a HashMap with values using the Map.of() method.

A Map is an interface that forms the basis for all map implementations, including a HashMap. The Map.of() method returns an unmodifiable map containing the number of elements you create.

If there are any duplicate keys, the method throws IllegalArgumentException and a NullPointerException if any key or value is null.

Output:

{1=david, 2=simon, 3=mary, 4=john, 5=jane}

Print HashMap using foreach method with keyset()

The HashMap get(Object key) is a method that returns the value that belongs to a particular key.

To get the key for every value in the HashMap, we use a for-loop with the keySet() method.

The key set method returns a set of unique keys, and we pass the keys to the get method to retrieve each value.

Output:

Print HashMap using Consumer with entrySet()

To use Consumer functional interface, you have to use the entrySet() method, which returns a Set containing the same type of key-value elements.

Since the Set is a Collection class that implements Iterable, use the forEach() method to print out the elements of the HashMap.

The forEach() is a method from the Iterable class, and it accepts only a Consumer as the parameter.

The for-each method iterates through the elements in the HashMap until they are exhausted as it prints them out using System.out.println.

Output:

1=A
2=B
3=C
4=D

Print HashMap using Arrays’s asList() method

To print out the elements of a HashMap using this class, pass the HashMap reference to the asList() method of the Arrays class.

This method will print out a list of elements in the HashMap as an Array.

When the reference of the array is is null, it throws a NullpointerException except where noted.

Output:

[{1=hardtail, 2=full supension, 3=speciality}]

Print HashMap using Collections’s singletonList()

The singletonList() is a static method from the Collections class hence no instantiation is required to use the method.

singletonList() returns an immutable list which is simply a list that can not be modified by either adding or removing elements from it once it has been created.

When you try to add or remove elements from the singleton list it throws an UnsupportedOperationException indicating that it is not supported in the list.

The singletonList method is generic meaning that it can handle any data type and, in our case just pass the HashMap reference and it will automatically infer the type.

Output:

[{1=how to print linked list in Java, 2=how to create ER diagrams, 3=deep dive into deadlock}]

Print HashMap using getkey() and getValue with entrySet()

To use the getKey() and getValue() methods, we use the entrySet() method which returns a Set of Map entries Map.Entry.

The map entry contains the key-value elements in the HashMap, and the elements are only available during the iteration period.

Since Set is a Collection the only way to reference the Map entry is by using an iterator inherited from the Iterable class.

A for loop will iterate through the elements in the Set of Map entries and print out the key for each value using the get key method and the value using the get value method.

Output:

1 = bungalow
2 = mansion
3 = flat

Print HashMap using BiConsumer

BiConsumer is a Functional Interface that represents an operation that accepts two arguments and returns no value.

The BiConsumer functional interface is a parameter of the forEach() method. The for-each method is inherited by the HashMap from the Map interface.

The type declared in the HashMap is the only type of value that will be accepted by the BiConsumer.

The functional interface will use the accept() method behind the scenes to receive the key and value parameters from the HashMap.

The action of our consumer will be printing out the elements in the HashMap. Note that if the action is null or an entry is removed during iteration, the for-each method will throw a NullPointerException and CurrentModificationException, respectively.

Output:

mary public
john doe
donald trump
peter parker

Print HashMap using Iterator

We can access the iterator() method through the entrySet() method, which returns a Set containing Map entries.

Since the Set class inherits from the Iterable interface we can return an Iterator then use the forEachRemaining() method to iterate through the elements.

The forEachRemaining is a method from the Iterator interface that we will use to print out the elements in the HashMap by passing a Consumer.

Output:

1=harry harry has no blessings
2=pride comes before a fall
3=Early bird catches the worm
4=the higher you go the cooler it becomes

Print HashMap using custom Objects

Whether you are creating a phone book or dictionary application, you must create custom objects for your HashMap.

We will create a HashMap that maps an id to a particular student object. The student id will be of type Integer.

Create a Student class with first name and last name properties, then add a constructor with the two fields and generate toString() method.

Create a HashMap with several objects of the Student and print them out using the getKey() and getValue() methods or any other approach that we have implemented in this article.

Output:

1 = Student{firstName=’john’, lastName=’doe’}
2 = Student{firstName=’abdirizack’, lastName=’mustafa’}
3 = Student{firstName=’mary’, lastName=’public’}

If you do not override toString() method in custom objects, then you will not get readable output.

Conclusion

In this article, you have learned different ways that you can use to print out the elements of a HashMap. The approaches covered include printing directly from the HashMap reference, using the get() method, using a Consumer, using Arrays.asList(),
using Collections.singletonList(), using getKey() and getValue(), using a BiConsumer, using an Iterator and finally custom objects.

That’s all about how to print HashMap in java.


import_contacts

You may also like:

Related Posts

  • Print LinkedList in java
    26 June

    Print LinkedList in java

    Table of ContentsJava inbuilt LinkedListPrint LinkedList using a for loopPrint LinkedList using Enhanced for loopPrint LinkedList using streamsPrint LinkedList using toString() methodPrint LinkedList using IteratorPrint LinkedList using custom objectsCustom singly LinkedListHow to print a custom singly LinkedListConclusion Java inbuilt LinkedList Java inbuilt LinkedList class uses doubly linked list as internal data structure to store its […]

  • Java Set to Array
    12 May

    Java Set to Array

    Table of Contents1. Using Java 8’s Stream2. Using toArray()3. Using toArray(IntFunction) [Java 11]4. Using System.arraycopy()5. Using Arrays.copyOf6. Using simple iteration7. Using Guava library7.1 Using FluentIterable7.2 Using Iterables In this post, we will learn java set to array conversion. There are many ways to convert set to an array. 1. Using Java 8’s Stream If you […]

  • Print ArrayList in java
    11 May

    Print ArrayList in Java

    Learn about how to print ArrayList in java in different ways.

  • 15 April

    How to Deep Copy Arraylist in Java

    Learn about how to create deep copy of ArrayList in different ways.

  • 02 October

    Initialize ArrayList with values in Java

    Table of ContentsUsing Arrays.asList()Initialize ArrayList with String valuesintialize ArrayList with Integer valuesintialize ArrayList with float valuesUsing Stream in Java 8Using Factory Method in java 9Using double braces In this article, we will learn to initialize ArrayList with values in Java. ArrayList is an implementation class of List interface in Java. It is used to store […]

  • 17 March

    PriorityQueue in Java 8

    Table of ContentsPriority Queue Data StructureSome Important PointsConstructorsMethodsCreating a PriorityQueueUsing No-arg constructor (Natural ordering)Using Custom Comparator In this post, we will see about Java 8 PriorityQueue. When the objects are supposed to be processed on the basis of their priority, in that scenario we use PriorityQueue. It’s a special type of queue (also, unbound queues) […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.