7/1/2023 0 Comments Java for loop hashmapHm.entrySet().iterator().forEachRemaining(entry-> As we have seen it earlier we can get the iterator of a Map through a Set package The forEachRemaining() method is newly added to Iterator interface in Java 8. Iterate a HashMap using Iterator.forEachRemaining() method The forEach() method of the HashMap takes up the BiConsumer functional interface as the argument and hence we can pass it a lambda expression that takes two inputs as argument key and value package Iterating through a HashMap using Lambda Expressions Iterate a HashMap using For-each Loop package The for-each loop (or) enhanced for loop in Java will invoke the iterator() method internally. entrySet() method returns Set interface, Set interface extends the Collection interface which in turn extends the Iterable Interface. Without further ado, let’s dive into the 5 more. Please check here if you haven’t read the Java tricky coding interview questions (part-1). The For-Each loop is available for all the classes which implement the Iterable interface. Tricky Java coding interview questions part 2. Iterator keySetIterator = hm.keySet().iterator() Note : If we use for-each loop dont forgot to check if the Map is not null. Since it is a Set again we can use the Iterator to iterate it. Method 1 : Java 8 forEach method Method 2: Looping by getting Entries of Map. The keySet() method returns the Set of all the Keys in the HashMap. Iterate through HashMap KeySet using Iterator ("Key : "+entry.getKey()+" Value : "+entry.getValue()) Iterator> entrySet = hm.entrySet().iterator() Now we can get the key-value pair easily using the getKey() and getValue() method. Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair. entrySet() returns a Set and a Set interface which extends the Collection interface and now on top of it, we can use the Iterator. In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations ( Stream operations) that looks similar to iterators from Iterable Interface. Map interface didn’t extend a Collection interface and hence it will not have its own iterator. Iterate through a HashMap EntrySet using Iterator 8 Best ways to Iterate through HashMap in Java Method 1.
0 Comments
Leave a Reply. |