Map<String, List<String>> result = anotherHashMap
    .entrySet().stream()                    // Stream over entry set
    .collect(Collectors.toMap(              // Collect final result map
        Map.Entry::getKey,                  // Key mapping is the same
        e -> e.getValue().stream()          // Stream over list
            .sorted(Comparator.comparingLong(MyObject::getPriority)) // Sort by priority
            .map(MyObject::getName)         // Apply mapping to MyObject
            .collect(Collectors.toList()))  // Collect mapping into list
        );

Essentially, you stream over each entry set and collect it into a new map. To compute the value in the new map, you stream over the List<MyOjbect> from the old map, sort, and apply a mapping and collection function to it. In this case I used MyObject::getName as the mapping and collected the resulting names into a list.

Answer from mkobit on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java collections › java map › iterate over a map in java
Iterate Over a Map in Java | Baeldung
December 16, 2024 - After defining an iterator object from the Map, we iterate through the values and find their sum. Since version 8, Java supports the forEach() method and lambda expressions, which can be used with maps.
Discussions

How To Iterate Over Hashmap In A For-Loop Context?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full - best also formatted as code block You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnjava
8
1
July 20, 2023
Iterate through hashmap using the classic for-loop
I suppose you could fetch the iterator of the entry set of the hashmap, and use that, but that seems a bit silly and basically ignores the index anyway. The reason you haven't found any examples is because a tradional for loop is mostly used when you need the index, but a HashMap isn't ordered so the index is meaningless. Iterator> iterator = myHashMap.entrySet().iterator(); for (;iterator.hasNext();) { Map.Entry myEntry = iterator.next(); } or even Iterator> iterator = myHashMap.entrySet().iterator(); int size = myHashMap.size(); for (int i = 0; i < size; i++) { Map.Entry myEntry = iterator.next(); } Though I really wouldn't use the last one. Using iterator.next() without first checking iterator.hasNext() is not really the correct way to use an iterator. More on reddit.com
🌐 r/javahelp
6
1
January 18, 2022
🌐
Mkyong
mkyong.com › home › java › java – how to iterate a hashmap
Java - How to Iterate a HashMap - Mkyong.com
April 8, 2019 - package com.mkyong.calculator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("web", 1024); map.put("database", 2048); map.put("static", 5120); System.out.println("Java 8 forEach loop"); map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value)); System.out.println("for entrySet()"); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); } System.out.println("Iterator"); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); } } }
🌐
Sentry
sentry.io › sentry answers › java › how to iterate over a hashmap in java
How to Iterate Over a HashMap in Java | Sentry
October 21, 2022 - Perhaps the most straightforward approach to iterating over a HashMap is to use a for-each loop to iterate over each entry. Using the HashMap.entrySet() will return a set view of the mappings or entries in the HashMap. import java.util.HashMap; ...
🌐
Medium
medium.com › @vino7tech › different-ways-to-iterate-over-a-hashmap-in-java-7b3f41e966e8
Different ways to iterate over a HashMap in Java | by Vinotech | Medium
October 2, 2024 - Different ways to iterate over a HashMap in Java A HashMap in Java is a part of the Java Collections Framework and implements the Map interface. It stores key-value pairs, allowing you to retrieve a …
🌐
GeeksforGeeks
geeksforgeeks.org › java › traverse-through-a-hashmap-in-java
Traverse Through a HashMap in Java - GeeksforGeeks
forEach() is a method of HashMap that is introduced in java 8. It is used to iterate through the hashmap and also reduces the number of lines of code as proposed below as follows:
Published   July 11, 2025
🌐
W3Schools
w3schools.com › java › java_hashmap.asp
Java HashMap
It is part of the java.util package and implements the Map interface. Instead of accessing elements by an index (like with ArrayList), you use a key to retrieve its associated value. A HashMap can store many different combinations, such as:
Find elsewhere
🌐
Medium
medium.com › @yadavsunil9699 › exploring-multiple-ways-to-iterate-through-maps-in-java-133441904b1e
Exploring Multiple Ways to Iterate Through Maps in Java | by Yadavsunil | Medium
September 8, 2023 - Iterates through values, ignoring keys. Convenient for scenarios where you only need the values. ... When you are interested in the values within the Map and don’t need the keys. Useful when performing operations solely on the values. ... Java 8 introduced functional programming features, making it easier to work with Maps using Streams. Map<String, Double> prices = new HashMap<>(); prices.put("Apple", 1.99); prices.put("Banana", 0.99); prices.put("Orange", 1.49); prices.forEach((key, value) -> System.out.println("Item: " + key + ", Price: " + value));
Top answer
1 of 15
11

Iterating a Map is very easy.

for (Object key : map.keySet()) {
   Object value = map.get(key);
   // Do your stuff
}

For instance, you have a Map<String, int> data;

for (Object key : data.keySet()) {
  int value = data.get(key);
}
2 of 15
9
package com.test;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Test {

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("ram", "ayodhya");
        map.put("krishan", "mathura");
        map.put("shiv", "kailash");

        System.out.println("********* Keys *********");
        Set<String> keys = map.keySet();
        for (String key : keys) {
            System.out.println(key);
        }

        System.out.println("********* Values *********");
        Collection<String> values = map.values();
        for (String value : values) {
            System.out.println(value);
        }

        System.out.println("***** Keys and Values (Using for each loop) *****");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out.println("***** Keys and Values (Using while loop) *****");
        Iterator<Entry<String, String>> entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) entries
                    .next();
            System.out.println("Key: " + entry.getKey() + "\t Value: "
                    + entry.getValue());
        }

        System.out
                .println("** Keys and Values (Using java 8 using lambdas )***");
        map.forEach((k, v) -> System.out
                .println("Key: " + k + "\t value: " + v));
    }
}
🌐
Coderanch
coderanch.com › t › 657075 › java › Set-HashMap-Objects-Streams
Set HashMap Objects using Streams (Features new in Java 8 forum at Coderanch)
I have the below code as per the traditional way to iterate and set the object value in hashmap as follows. I don't want to initialize the obj inside stream.
🌐
Reddit
reddit.com › r/learnjava › how to iterate over hashmap in a for-loop context?
r/learnjava on Reddit: How To Iterate Over Hashmap In A For-Loop Context?
July 20, 2023 -

I have a hashmap where each set's key is an Integer and the value is a custom inner class called node.

My for loop currently looks like this (hm is the variable that holds the hashmap):

for(int x=0; x<hm.entrySet().size(); x++){

    HashMap.Entry<Integer, node> currSet = hm.entrySet();
}

I know I need to do something to the " hm.entrySet() " inside the for-loop in order to access the set which is at index x. How do I do that?

Ideally I would have liked " hm.entrySet().get(x) " (the same syntax as accessing an arraylist) but that doesn't work.

What is the equivalent of " get(x) " in a situation like this?

🌐
Reddit
reddit.com › r/javahelp › iterate through hashmap using the classic for-loop
r/javahelp on Reddit: Iterate through hashmap using the classic for-loop
January 18, 2022 -

Hello!

Is it possible to iterate through a hashmap using the classic for-loop instead of for-each?

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Looking online, i've seen a bunch of methods to iterate through a hashmap that are indeed more efficient, but i've never seen the classic for-loop ever used. Just wondering if this is possible or not, as i've never seen an example so far.

Thanks!

Top answer
1 of 3
3
I suppose you could fetch the iterator of the entry set of the hashmap, and use that, but that seems a bit silly and basically ignores the index anyway. The reason you haven't found any examples is because a tradional for loop is mostly used when you need the index, but a HashMap isn't ordered so the index is meaningless. Iterator> iterator = myHashMap.entrySet().iterator(); for (;iterator.hasNext();) { Map.Entry myEntry = iterator.next(); } or even Iterator> iterator = myHashMap.entrySet().iterator(); int size = myHashMap.size(); for (int i = 0; i < size; i++) { Map.Entry myEntry = iterator.next(); } Though I really wouldn't use the last one. Using iterator.next() without first checking iterator.hasNext() is not really the correct way to use an iterator.
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Scientech Easy
scientecheasy.com › home › blog › how to iterate hashmap in java
How to Iterate HashMap in Java - Scientech Easy
May 16, 2025 - Using lambda expression to iterate ... benefit from the functional programming features provided by Java 8. We will use forEach() method along with a lambda expression to iterate over hashmap entries....
🌐
Interview Kickstart
interviewkickstart.com › home › blogs › learn › how to iterate a map in java
How to Iterate a Map in Java | Interview Kickstart
September 25, 2024 - In the latest versions of Java, like Java 8, we can iterate a Map using the inbuilt Map.forEach(action) method and lambda expressions in Java. Here’s the code: // Using forEach(action) method. import java.util.Map; import java.util.HashMap; ...
🌐
Makeseleniumeasy
makeseleniumeasy.com › 2023 › 03 › 24 › how-to-iterate-map-in-java-using-stream-and-lambda
How To Iterate Map In Java Using Stream and Lambda?
March 24, 2023 - We learned to Iterate a Map In Java using keySet(), entrySet(), values(), and iterator(). In this post, We will learn how can we use Java 8 features like Lambda functions and Stream APIs · We can use forEach() method overridden in the HashSet class. It requires less code but you need to be ...
🌐
Quora
quora.com › How-do-you-iterate-over-a-Hash-map-of-arraylists-of-String-in-Java
How to iterate over a Hash map of arraylists of String in Java - Quora
Answer (1 of 3): This can be done quite compactly in Java 8+: [code]map.values().stream().flatMap(List::stream).forEach(System.out::println) [/code]This will flatten a [code ]Map [/code] , and print the result out to the console. You can run the following test to verif...
🌐
Java Development Journal
javadevjournal.com › home › how to iterate through a map in java
How to Iterate Through a Map in Java | Java Development Journal
October 28, 2020 - Using iterator. Using for loop. Java 8 came with lots of features and enhancements. With Java 8, forEach method accepts lambda expressions and also provides the option to use the new Stream API. import java.util.HashMap; import java.util.Map; ...
🌐
DevQA
devqa.io › 4-different-ways-iterate-map-java
Different Ways to Iterate Through a Map in Java
November 10, 2019 - As of Java 8, we can use the forEach method as well as the iterator class to loop over a map. Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " ...
🌐
YouTube
youtube.com › java guides
5 Best Ways to Iterate Over HashMap in Java - YouTube
In this video, we will discuss five best ways to iterate over a HashMap in Java with examples.1. Iterate through a HashMap EntrySet using Iterator2. Iterate ...
Published   March 11, 2020
Views   39K
🌐
YouTube
m.youtube.com › watch
5 Different ways to iterate Hashmap in java
We cannot provide a description for this page right now