{"id":15463,"date":"2021-06-30T20:13:58","date_gmt":"2021-06-30T14:43:58","guid":{"rendered":"https:\/\/java2blog.com\/?p=15463"},"modified":"2021-06-30T20:13:58","modified_gmt":"2021-06-30T14:43:58","slug":"print-hashmap-in-java","status":"publish","type":"post","link":"https:\/\/java2blog.com\/print-hashmap-in-java\/","title":{"rendered":"Print HashMap in Java"},"content":{"rendered":"<p>In this article, we will see how to print HashMap in java using different method.<br \/>\n<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Print_from_the_HashMap_Reference\">Print from the HashMap Reference<\/a><\/li><li><a href=\"#Print_HashMap_using_foreach_method_with_keyset\">Print HashMap using foreach method with keyset()<\/a><\/li><li><a href=\"#Print_HashMap_using_Consumer_with_entrySet\">Print HashMap using Consumer with entrySet()<\/a><\/li><li><a href=\"#Print_HashMap_using_Arrays8217s_asList_method\">Print HashMap using Arrays&#8217;s asList() method<\/a><\/li><li><a href=\"#Print_HashMap_using_Collections8217s_singletonList\">Print HashMap using Collections&#8217;s singletonList()<\/a><\/li><li><a href=\"#Print_HashMap_using_getkey_and_getValue_with_entrySet\">Print HashMap using getkey() and getValue with entrySet()<\/a><\/li><li><a href=\"#Print_HashMap_using_BiConsumer\">Print HashMap using BiConsumer<\/a><\/li><li><a href=\"#Print_HashMap_using_Iterator\">Print HashMap using Iterator<\/a><\/li><li><a href=\"#Print_HashMap_using_custom_Objects\">Print HashMap using custom Objects<\/a><\/li><li><a href=\"#Conclusion\">Conclusion<\/a><\/li><\/ul><\/div>\n\n<h2><span id=\"Print_from_the_HashMap_Reference\">Print from the HashMap Reference<\/span><\/h2>\n<p>This is the most basic and easiest method to print out <a href=\"https:\/\/java2blog.com\/hashmap-in-java-with-examples\/\" title=\"HashMap in java\">HashMap in java<\/a>. Pass the HashMap reference to the <a href=\"https:\/\/java2blog.com\/system-out-println-java\/\" title=\"System.out.println\">System.out.println<\/a>, and the HashMap will output the key-value of the elements enclosed in curly brackets.<\/p>\n<p>We will use a HashMap <a href=\"https:\/\/java2blog.com\/constructor-java\/\" title=\"constructor\">constructor<\/a> and a pass <code>Map<\/code> of elements to the constructor, which provides an easier way to initialize a HashMap with values using the <code>Map.of()<\/code> method.<\/p>\n<p>A Map is an interface that forms the basis for all map implementations, including a HashMap. The <code>Map.of()<\/code> method returns an unmodifiable map containing the number of elements you create.<\/p>\n<p>If there are any duplicate keys, the method throws <code>IllegalArgumentException<\/code> and a <a href=\"https:\/\/java2blog.com\/exception-thread-main-java-lang-nullpointerexception\/\" title=\"NullPointerException\">NullPointerException<\/a> if any key or value is <code>null<\/code>.<\/p>\n<pre code=\"java\">\npublic static void main(String[] args) {\n        HashMap<Integer, String> names = new HashMap<>(Map.of(\n                1, \"david\",\n                2, \"simon\",\n                3, \"mary\",\n                4, \"john\",\n                5, \"jane\"\n        ));\n        System.out.println(names);\n}\n<\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\n{1=david, 2=simon, 3=mary, 4=john, 5=jane}\n<\/div>\n<h2><span id=\"Print_HashMap_using_foreach_method_with_keyset\">Print HashMap using foreach method with keyset()<\/span><\/h2>\n<p>The HashMap <code>get(Object key)<\/code> is a method that returns the value that belongs to a particular key.<\/p>\n<p>To get the key for every value in the HashMap, we use a for-loop with the <code>keySet()<\/code> method.<\/p>\n<p>The key set method returns a set of unique keys, and we pass the keys to the get method to retrieve each value.<\/p>\n<pre code=\"java\">\npublic static void main(String[] arg){\n    HashMap<Integer,String> emails = new HashMap<>(Map.of(\n                1,\"mary@domain.com\",\n                2,\"john@domain.com\",\n                3,\"jane@domain.com\"\n        ));\n        for (Integer key: emails.keySet()){\n            System.out.println(key +\" = \"+emails.get(key));\n        }\n}\n<\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\n1 = mary@domain.com<br \/>\n2 = john@domain.com<br \/>\n3 = jane@domain.com\n<\/div>\n<h2><span id=\"Print_HashMap_using_Consumer_with_entrySet\">Print HashMap using Consumer with entrySet()<\/span><\/h2>\n<p>To use <a href=\"https:\/\/java2blog.com\/java-8-consumer-example\/\" title=\"Consumer functional interface\">Consumer functional interface<\/a>, you have to use the <code>entrySet()<\/code> method, which returns a <code>Set<\/code> containing the same type of key-value elements.<\/p>\n<p>Since the <code>Set<\/code> is a <code>Collection<\/code> class that implements <code>Iterable<\/code>, use the <code>forEach()<\/code> method to print out the elements of the HashMap.<\/p>\n<p>The <a href=\"https:\/\/java2blog.com\/java-8-foreach-examples\/\" title=\"forEach()\">forEach()<\/a> is a method from the <code>Iterable<\/code> class, and it accepts only a Consumer as the parameter.<\/p>\n<p>The for-each method iterates through the elements in the HashMap until they are exhausted as it prints them out using System.out.println.<\/p>\n<pre code=\"java\">\npublic static void main(String[] arg){\n    HashMap<Integer, Character> marks = new HashMap<>(Map.of(\n           1,'A',\n           2,'B',\n           3,'C',\n           4,'D'\n        ));\n    marks.entrySet().forEach(System.out::println);\n}\n<\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\n1=A<br \/>\n2=B<br \/>\n3=C<br \/>\n4=D\n<\/div>\n<h2><span id=\"Print_HashMap_using_Arrays8217s_asList_method\">Print HashMap using Arrays&#8217;s asList() method<\/span><\/h2>\n<p>To print out the elements of a HashMap using this class, pass the HashMap reference to the <code>asList()<\/code> method of the <code>Arrays<\/code> class.<\/p>\n<p>This method will print out a list of elements in the HashMap as an Array.<\/p>\n<p>When the reference of the array is is <code>null<\/code>, it throws a <a href=\"https:\/\/java2blog.com\/exception-thread-main-java-lang-nullpointerexception\/\" title=\"NullpointerException\">NullpointerException<\/a> except where noted.<\/p>\n<pre code=\"java\">\npublic static void main(String[] arg){\n     HashMap<Integer, String> bikes = new HashMap<>(Map.of(\n                1,\"hardtail\",\n                2,\"full supension\",\n                3,\"speciality\"\n        ));\n\n    System.out.println(Arrays.asList(bikes));\n}\n<\/pre>\n<p>Output:<\/p>\n<div code=\"java\">\n[{1=hardtail, 2=full supension, 3=speciality}]\n<\/div>\n<h2><span id=\"Print_HashMap_using_Collections8217s_singletonList\">Print HashMap using Collections&#8217;s singletonList()<\/span><\/h2>\n<p>The <code>singletonList()<\/code> is a static method from the <code>Collections<\/code> class hence no instantiation is required to use the method.<\/p>\n<p><code>singletonList()<\/code> returns an <a href=\"https:\/\/java2blog.com\/how-to-create-immutable-class-in-java\/\" title=\"immutable\">immutable<\/a> list which is simply a list that can not be modified by either adding or removing elements from it once it has been created.<\/p>\n<p>When you try to add or remove elements from the singleton list it throws an <code>UnsupportedOperationException<\/code> indicating that it is not supported in the list.<\/p>\n<p>The <code>singletonList<\/code> method is generic meaning that it can handle any <a href=\"https:\/\/java2blog.com\/data-types-in-java\/\" title=\"data type\">data type<\/a> and, in our case just pass the HashMap reference and it will automatically infer the type.<\/p>\n<pre code=\"java\">\npublic static void main(String[] arg){\n      HashMap<Integer, String> courses = new HashMap<>(Map.of(\n                1,\"how to print linked list in Java\",\n                2,\"how to create ER diagrams\",\n                3,\"deep dive into deadlock\"\n        ));\n    System.out.println(Collections.singletonList(courses));\n}\n<\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\n[{1=how to print linked list in Java, 2=how to create ER diagrams, 3=deep dive into deadlock}]\n<\/div>\n<h2><span id=\"Print_HashMap_using_getkey_and_getValue_with_entrySet\">Print HashMap using getkey() and getValue with entrySet()<\/span><\/h2>\n<p>To use the <code>getKey()<\/code> and <code>getValue()<\/code> methods, we use the <code>entrySet()<\/code> method which returns a Set of Map entries <code>Map.Entry<\/code>.<\/p>\n<p>The map entry contains the key-value elements in the HashMap, and the elements are only available during the iteration period.<\/p>\n<p>Since <code>Set<\/code> is a Collection the only way to reference the Map entry is by using an iterator inherited from the <code>Iterable<\/code> class.<\/p>\n<p>A <a href=\"https:\/\/java2blog.com\/for-loop-java-example\/\" title=\"for loop\">for loop<\/a> 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.<\/p>\n<pre code=\"java\">\npublic static void main(String[] arg){\n        HashMap<Integer,String> houses = new HashMap<>(Map.of(\n                1,\"bungalow\",\n                2,\"mansion\",\n                3,\"flat\"\n        ));\n        for (Map.Entry<Integer,String> theHouse :houses.entrySet()){\n            System.out.println(theHouse.getKey() +\" = \"+theHouse.getValue());\n        }\n}\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<div class=\"content-box-green\">\n1 = bungalow<br \/>\n2 = mansion<br \/>\n3 = flat\n<\/div>\n<h2><span id=\"Print_HashMap_using_BiConsumer\">Print HashMap using BiConsumer<\/span><\/h2>\n<p><a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/11\/docs\/api\/java.base\/java\/util\/function\/BiConsumer.html\" target=\"_blank\" rel=\"noopener\">BiConsumer<\/a> is a Functional Interface that represents an operation that accepts two arguments and returns no value.<\/p>\n<p>The BiConsumer <a href=\"https:\/\/java2blog.com\/java-8-functional-interface-example\/\" title=\"functional interface\">functional interface<\/a> is a parameter of the <code>forEach()<\/code> method. The for-each method is inherited by the HashMap from the <code>Map<\/code> interface.<\/p>\n<p>The type declared in the HashMap is the only type of value that will be accepted by the <code>BiConsumer<\/code>.<\/p>\n<p>The functional interface will use the <code>accept()<\/code> method behind the scenes to receive the key and value parameters from the HashMap.<\/p>\n<p>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 <a href=\"https:\/\/java2blog.com\/exception-thread-main-java-lang-nullpointerexception\/\" title=\"NullPointerException\">NullPointerException<\/a> and <code>CurrentModificationException<\/code>, respectively.<\/p>\n<pre code=\"java\">\npublic static void main(String[] arg){\n    HashMap<String, String> mapNames = new HashMap<>(Map.of(\n                \"john\",\"doe\",\n                \"mary\",\"public\",\n                \"peter\",\"parker\",\n                \"donald\",\"trump\"\n        ));\n    BiConsumer<String, String> firstAndLastNameBiConsumer = (firstName, lastName) -> {\n        System.out.println(firstName + \" \" + lastName);\n    };\n    mapNames.forEach(firstAndLastNameBiConsumer);\n}\n<\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\nmary public<br \/>\njohn doe<br \/>\ndonald trump<br \/>\npeter parker\n<\/div>\n<h2><span id=\"Print_HashMap_using_Iterator\">Print HashMap using Iterator<\/span><\/h2>\n<p>We can access the <code>iterator()<\/code> method through the <code>entrySet()<\/code> method, which returns a Set containing Map entries.<\/p>\n<p>Since the Set class inherits from the Iterable interface we can return an <a href=\"https:\/\/docs.oracle.com\/en\/java\/javase\/11\/docs\/api\/java.base\/java\/util\/Iterator.html\" target=\"_blank\" rel=\"noopener\">Iterator<\/a> then use the <code>forEachRemaining()<\/code> method to iterate through the elements.<\/p>\n<p>The <code>forEachRemaining<\/code> is a method from the Iterator interface that we will use to print out the elements in the HashMap by passing a Consumer.<\/p>\n<pre code=\"java\">\npublic static void main(String[] arg){\n    HashMap<Integer, String> quotes = new HashMap<>(Map.of(\n                    1,\"harry harry has no blessings\",\n                    2,\"pride comes before a fall\",\n                    3,\"Early bird catches the worm\",\n                    4,\"the higher you go the cooler it becomes\"\n            ));\n        Iterator<Map.Entry<Integer, String>> iterator = quotes.entrySet().iterator();\n        iterator.forEachRemaining(System.out::println);\n\n}\n<\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\n1=harry harry has no blessings<br \/>\n2=pride comes before a fall<br \/>\n3=Early bird catches the worm<br \/>\n4=the higher you go the cooler it becomes\n<\/div>\n<h2><span id=\"Print_HashMap_using_custom_Objects\">Print HashMap using custom Objects<\/span><\/h2>\n<p>Whether you are creating a phone book or dictionary application, you must create custom objects for your HashMap.<\/p>\n<p>We will create a <a href=\"https:\/\/java2blog.com\/hashmap-in-java-with-examples\/\" title=\"HashMap\">HashMap<\/a> that maps an id to a particular student object. The student id will be of type Integer.<\/p>\n<p>Create a <code>Student<\/code> class with first name and last name properties, then add a constructor with the two fields and generate <code>toString()<\/code> method.<\/p>\n<pre code=\"java\">\npublic class Student{\n        private String firstName;\n        private String lastName;\n\n        public Student(String firstName, String lastName) {\n            this.firstName = firstName;\n            this.lastName = lastName;\n        }\n        @Override\n        public String toString() {\n             return \"Student{\" +\n                \"firstName='\" + firstName + '\\'' +\n                \", lastName='\" + lastName + '\\'' +\n                '}';\n    }\n }\n<\/pre>\n<p>Create a HashMap with several objects of the <code>Student<\/code> and print them out using the <code>getKey()<\/code> and <code>getValue()<\/code> methods or any other approach that we have implemented in this article.<\/p>\n<pre code=\"java\">\npublic static void main(String[] arg){\n    HashMap<Integer, Student> students = new HashMap<>(Map.of(\n                1,new Student(\"john\",\"doe\"),\n                2,new Student(\"abdirizack\",\"mustafa\"),\n                3,new Student(\"mary\",\"public\")\n        ));\n\n    for (Map.Entry<Integer,Student> studentEntry: students.entrySet()){\n        System.out.println(studentEntry.getKey()+ \" = \"+ studentEntry.getValue());\n    }\n}\n<\/pre>\n<p>Output:<\/p>\n<div class=\"content-box-green\">\n1 = Student{firstName=&#8217;john&#8217;, lastName=&#8217;doe&#8217;}<br \/>\n2 = Student{firstName=&#8217;abdirizack&#8217;, lastName=&#8217;mustafa&#8217;}<br \/>\n3 = Student{firstName=&#8217;mary&#8217;, lastName=&#8217;public&#8217;}\n<\/div>\n<blockquote>\n<p>If you do not override <code>toString()<\/code> method in custom objects, then you will not get readable output.<\/p>\n<h2><span id=\"Conclusion\">Conclusion<\/span><\/h2>\n<p>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 <code>get()<\/code> method, using a <code>Consumer<\/code>, using <code>Arrays.asList()<\/code>,<br \/>\nusing <code>Collections.singletonList()<\/code>, using <code>getKey()<\/code> and <code>getValue()<\/code>, using a <code>BiConsumer<\/code>, using an <code>Iterator<\/code> and finally custom objects.<\/p>\n<\/blockquote>\n<p>That&#8217;s all about how to print HashMap in java.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsPrint from the HashMap ReferencePrint HashMap using foreach method with keyset()Print HashMap using Consumer with entrySet()Print HashMap using Arrays&#8217;s asList() methodPrint HashMap using Collections&#8217;s singletonList()Print HashMap using getkey() and getValue with entrySet()Print HashMap using BiConsumerPrint HashMap using IteratorPrint HashMap using custom ObjectsConclusion In this article, we will see how to print HashMap in [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":15534,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[44],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/15463"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=15463"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/15463\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/15534"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=15463"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=15463"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=15463"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}