This question already has answers here:
How do I efficiently iterate over each entry in a Java Map?
(46 answers)
Closed 3 years ago.
What's the best way to iterate over the items in a HashMap?
If you're only interested in the keys, you can iterate through the keySet() of the map:
Map<String, Object> map = ...;
for (String key : map.keySet()) {
// ...
}
If you only need the values, use values():
for (Object value : map.values()) {
// ...
}
Finally, if you want both the key and value, use entrySet():
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).
Iterate through the entrySet() like so:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
Read more about Map.
Extracted from the reference How to Iterate Over a Map in Java:
There are several ways of iterating over a Map in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)
Method #1: Iterating over entries using a For-Each loop.
This is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Note that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.
Method #2: Iterating over keys or values using a For-Each loop.
If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
// Iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
This method gives a slight performance advantage over entrySet iteration (about 10% faster) and is more clean.
Method #3: Iterating using Iterator.
Using Generics:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
You can also use same technique to iterate over keySet or values.
This method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to Javadoc.
From a performance point of view this method is equal to a For-Each iteration.
Method #4: Iterating over keys and searching for values (inefficient).
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
This might look like a cleaner alternative for method #1, but in practice it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.
Conclusion:
If you need only keys or values from the map, use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1.
for (Map.Entry<String, String> item : hashMap.entrySet()) {
String key = item.getKey();
String value = item.getValue();
}
You can iterate through the entries in a Map in several ways. Get each key and value like this:
Map<?,?> map = new HashMap<Object, Object>();
for(Entry<?, ?> e: map.entrySet()){
System.out.println("Key " + e.getKey());
System.out.println("Value " + e.getValue());
}
Or you can get the list of keys with
Collection<?> keys = map.keySet();
for(Object key: keys){
System.out.println("Key " + key);
System.out.println("Value " + map.get(key));
}
If you just want to get all of the values and aren't concerned with the keys, you can use:
Collection<?> values = map.values();
Smarter:
for (String key : hashMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
It depends. If you know you're going to need both the key and the value of every entry, then go through the entrySet. If you just need the values, then there's the values() method. And if you just need the keys, then use keyset().
A bad practice would be to iterate through all of the keys, and then within the loop, always do map.get(key) to get the value. If you're doing that, then the first option I wrote is for you.
Related
This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 5 years ago.
I was doing:
for (Object key : map.keySet())
if (something)
map.remove(key);
which threw a ConcurrentModificationException, so i changed it to:
for (Object key : new ArrayList<Object>(map.keySet()))
if (something)
map.remove(key);
this, and any other procedures that modify the map are in synchronized blocks.
is there a better solution?
Here is a code sample to use the iterator in a for loop to remove the entry.
Map<String, String> map = new HashMap<String, String>() {
{
put("test", "test123");
put("test2", "test456");
}
};
for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, String> entry = it.next();
if(entry.getKey().equals("test")) {
it.remove();
}
}
As of Java 8 you could do this as follows:
map.entrySet().removeIf(e -> <boolean expression>);
Oracle Docs: entrySet()
The set is backed by the map, so changes to the map are reflected in the set, and vice-versa
Use a real iterator.
Iterator<Object> it = map.keySet().iterator();
while (it.hasNext())
{
it.next();
if (something)
it.remove();
}
Actually, you might need to iterate over the entrySet() instead of the keySet() to make that work.
is there a better solution?
Well, there is, definitely, a better way to do so in a single statement, but that depends on the condition based on which elements are removed.
For eg: remove all those elements where value is test, then use below:
map.values().removeAll(Collections.singleton("test"));
UPDATE
It can be done in a single line using Lambda expression in Java 8.
map.entrySet().removeIf(e-> <boolean expression> );
I know this question is way too old, but there isn't any harm in updating the better way to do the things :)
ConcurrentHashMap
You can use java.util.concurrent.ConcurrentHashMap.
It implements ConcurrentMap (which extends the Map interface).
E.g.:
Map<Object, Content> map = new ConcurrentHashMap<Object, Content>();
for (Object key : map.keySet()) {
if (something) {
map.remove(key);
}
}
This approach leaves your code untouched. Only the map type differs.
Java 8 support a more declarative approach to iteration, in that we specify the result we want rather than how to compute it. Benefits of the new approach are that it can be more readable, less error prone.
public static void mapRemove() {
Map<Integer, String> map = new HashMap<Integer, String>() {
{
put(1, "one");
put(2, "two");
put(3, "three");
}
};
map.forEach( (key, value) -> {
System.out.println( "Key: " + key + "\t" + " Value: " + value );
});
map.keySet().removeIf(e->(e>2)); // <-- remove here
System.out.println("After removing element");
map.forEach( (key, value) -> {
System.out.println( "Key: " + key + "\t" + " Value: " + value );
});
}
And result is as follows:
Key: 1 Value: one
Key: 2 Value: two
Key: 3 Value: three
After removing element
Key: 1 Value: one
Key: 2 Value: two
You have to use Iterator to safely remove element while traversing a map.
I agree with Paul Tomblin. I usually use the keyset's iterator, and then base my condition off the value for that key:
Iterator<Integer> it = map.keySet().iterator();
while(it.hasNext()) {
Integer key = it.next();
Object val = map.get(key);
if (val.shouldBeRemoved()) {
it.remove();
}
}
An alternative, more verbose way
List<SomeObject> toRemove = new ArrayList<SomeObject>();
for (SomeObject key: map.keySet()) {
if (something) {
toRemove.add(key);
}
}
for (SomeObject key: toRemove) {
map.remove(key);
}
And this should work as well..
ConcurrentMap<Integer, String> running = ... create and populate map
Set<Entry<Integer, String>> set = running.entrySet();
for (Entry<Integer, String> entry : set)
{
if (entry.getKey()>600000)
{
set.remove(entry.getKey());
}
}
Maybe you can iterate over the map looking for the keys to remove and storing them in a separate collection. Then remove the collection of keys from the map. Modifying the map while iterating is usually frowned upon. This idea may be suspect if the map is very large.
Set s=map.entrySet();
Iterator iter = s.iterator();
while (iter.hasNext()) {
Map.Entry entry =(Map.Entry)iter.next();
if("value you need to remove".equals(entry.getKey())) {
map.remove();
}
}
This question already has answers here:
How do I efficiently iterate over each entry in a Java Map?
(46 answers)
Closed 3 years ago.
What's the best way to iterate over the items in a HashMap?
If you're only interested in the keys, you can iterate through the keySet() of the map:
Map<String, Object> map = ...;
for (String key : map.keySet()) {
// ...
}
If you only need the values, use values():
for (Object value : map.values()) {
// ...
}
Finally, if you want both the key and value, use entrySet():
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
One caveat: if you want to remove items mid-iteration, you'll need to do so via an Iterator (see karim79's answer). However, changing item values is OK (see Map.Entry).
Iterate through the entrySet() like so:
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
Read more about Map.
Extracted from the reference How to Iterate Over a Map in Java:
There are several ways of iterating over a Map in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)
Method #1: Iterating over entries using a For-Each loop.
This is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Note that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.
Method #2: Iterating over keys or values using a For-Each loop.
If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Iterating over keys only
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
// Iterating over values only
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
This method gives a slight performance advantage over entrySet iteration (about 10% faster) and is more clean.
Method #3: Iterating using Iterator.
Using Generics:
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer)entry.getKey();
Integer value = (Integer)entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
You can also use same technique to iterate over keySet or values.
This method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to Javadoc.
From a performance point of view this method is equal to a For-Each iteration.
Method #4: Iterating over keys and searching for values (inefficient).
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
This might look like a cleaner alternative for method #1, but in practice it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.
Conclusion:
If you need only keys or values from the map, use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1.
for (Map.Entry<String, String> item : hashMap.entrySet()) {
String key = item.getKey();
String value = item.getValue();
}
You can iterate through the entries in a Map in several ways. Get each key and value like this:
Map<?,?> map = new HashMap<Object, Object>();
for(Entry<?, ?> e: map.entrySet()){
System.out.println("Key " + e.getKey());
System.out.println("Value " + e.getValue());
}
Or you can get the list of keys with
Collection<?> keys = map.keySet();
for(Object key: keys){
System.out.println("Key " + key);
System.out.println("Value " + map.get(key));
}
If you just want to get all of the values and aren't concerned with the keys, you can use:
Collection<?> values = map.values();
Smarter:
for (String key : hashMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + map.get(key));
}
It depends. If you know you're going to need both the key and the value of every entry, then go through the entrySet. If you just need the values, then there's the values() method. And if you just need the keys, then use keyset().
A bad practice would be to iterate through all of the keys, and then within the loop, always do map.get(key) to get the value. If you're doing that, then the first option I wrote is for you.
I am trying to simply print all key/value pair(s) in a ConcurrentHashMap.
I found this code online that I thought would do it, but it seems to be getting information about the buckets/hashcode. Actually to be honest the output it quite strange, its possible my program is incorrect, but I first want to make sure this part is what I want to be using.
for (Entry<StringBuilder, Integer> entry : wordCountMap.entrySet()) {
String key = entry.getKey().toString();
Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
This gives output for about 10 different keys, with counts that seem to be the sum of the number of total inserts into the map.
I tested your code and works properly. I've added a small demo with another way to print all the data in the map:
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey().toString();
Integer value = entry.getValue();
System.out.println("key, " + key + " value " + value);
}
The HashMap has forEach as part of its structure. You can use that with a lambda expression to print out the contents in a one liner such as:
map.forEach((k,v)-> System.out.println(k+", "+v));
or
map.forEach((k,v)-> System.out.println("key: "+k+", value: "+v));
You can do something like
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
Integer value = map.get(key);
System.out.println(key + " " + value);
}
Here 'map' is your concurrent HashMap.
//best and simple way to show keys and values
//initialize map
Map<Integer, String> map = new HashMap<Integer, String>();
//Add some values
map.put(1, "Hi");
map.put(2, "Hello");
// iterate map using entryset in for loop
for(Entry<Integer, String> entry : map.entrySet())
{ //print keys and values
System.out.println(entry.getKey() + " : " +entry.getValue());
}
//Result :
1 : Hi
2 : Hello
The ConcurrentHashMap is very similar to the HashMap class, except that ConcurrentHashMap offers internally maintained concurrency. It means you do not need to have synchronized blocks when accessing ConcurrentHashMap in multithreaded application.
To get all key-value pairs in ConcurrentHashMap, below code which is similar to your code works perfectly:
//Initialize ConcurrentHashMap instance
ConcurrentHashMap<String, Integer> m = new ConcurrentHashMap<String, Integer>();
//Print all values stored in ConcurrentHashMap instance
for each (Entry<String, Integer> e : m.entrySet()) {
System.out.println(e.getKey()+"="+e.getValue());
}
Above code is reasonably valid in multi-threaded environment in your application. The reason, I am saying 'reasonably valid' is that, above code yet provides thread safety, still it can decrease the performance of application.
Hope this helps you.
Work 100% sure try this code for the get all hashmap key and value
static HashMap<String, String> map = new HashMap<>();
map.put("one" " a " );
map.put("two" " b " );
map.put("three" " c " );
map.put("four" " d " );
just call this method whenever you want to show the HashMap value
private void ShowHashMapValue() {
/**
* get the Set Of keys from HashMap
*/
Set setOfKeys = map.keySet();
/**
* get the Iterator instance from Set
*/
Iterator iterator = setOfKeys.iterator();
/**
* Loop the iterator until we reach the last element of the HashMap
*/
while (iterator.hasNext()) {
/**
* next() method returns the next key from Iterator instance.
* return type of next() method is Object so we need to do DownCasting to String
*/
String key = (String) iterator.next();
/**
* once we know the 'key', we can get the value from the HashMap
* by calling get() method
*/
String value = map.get(key);
System.out.println("Key: " + key + ", Value: " + value);
}
}
I have following LinkedHashMap declaration.
LinkedHashMap<String, ArrayList<String>> test1
my point is how can i iterate through this hash map.
I want to do this following, for each key get the corresponding arraylist and print the values of the arraylist one by one against the key.
I tried this but get only returns string,
String key = iterator.next().toString();
ArrayList<String> value = (ArrayList<String> )test1.get(key)
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// now work with key and value...
}
By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.
I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.
This should work:
// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());
// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
String key = entry.getKey();
List<String>value = entry.getValue();
// ...
}
or you can use
// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
List<String>value = test1.get(key);
// ...
}
You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.
In Java 8:
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});
You can use the entry set and iterate over the entries which allows you to access both, key and value, directly.
for (Entry<String, ArrayList<String>> entry : test1.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
I tried this but get only returns string
Why do you think so? The method get returns the type E for which the generic type parameter was chosen, in your case ArrayList<String>.
// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
// iterate over each entry
for(String item : entry.getValue()){
// print the map's key with each value in the ArrayList
System.out.println(entry.getKey() + ": " + item);
}
}
I have a HashMap:
private HashMap<TypeKey, TypeValue> example = new HashMap<TypeKey, TypeValue>();
Now I would like to run through all the values and print them.
I wrote this:
for (TypeValue name : this.example.keySet()) {
System.out.println(name);
}
It doesn't seem to work.
What is the problem?
EDIT:
Another question: Is this collection zero based? I mean if it has 1 key and value will the size be 0 or 1?
keySet() only returns a set of keys from your hash map, you should iterate this key set and the get the value from the hash map using these keys.
In your example, the type of the hash map's key is TypeKey, but you specified TypeValue in your generic for-loop, so it cannot be compiled. You should change it to:
for (TypeKey name: example.keySet()) {
String key = name.toString();
String value = example.get(name).toString();
System.out.println(key + " " + value);
}
Update for Java8:
example.entrySet().forEach(entry -> {
System.out.println(entry.getKey() + " " + entry.getValue());
});
If you don't require to print key value and just need the hash map value, you can use others' suggestions.
Another question: Is this collection is zero base? I mean if it has 1 key and value will it size be 0 or 1?
The collection returned from keySet() is a Set. You cannot get the value from a set using an index, so it is not a question of whether it is zero-based or one-based. If your hash map has one key, the keySet() returned will have one entry inside, and its size will be 1.
A simple way to see the key value pairs:
Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
System.out.println(Arrays.asList(map)); // method 1
System.out.println(Collections.singletonList(map)); // method 2
Both method 1 and method 2 output this:
[{b=2, a=1}]
Assuming you have a Map<KeyType, ValueType>, you can print it like this:
for (Map.Entry<KeyType, ValueType> entry : map.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
To print both key and value, use the following:
for (Object objectName : example.keySet()) {
System.out.println(objectName);
System.out.println(example.get(objectName));
}
You have several options
Get map.values() , which gets the values, not the keys
Get the map.entrySet() which has both
Get the keySet() and for each key call map.get(key)
For me this simple one line worked well:
Arrays.toString(map.entrySet().toArray())
A simple print statement with the variable name which contains the reference of the Hash Map would do :
HashMap<K,V> HM = new HashMap<>(); //empty
System.out.println(HM); //prints key value pairs enclosed in {}
This works because the toString()method is already over-ridden in the AbstractMap class which is extended by the HashMap Class
More information from the documentation
Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).
map.forEach((key, value) -> System.out.println(key + " " + value));
Using java 8 features
You want the value set, not the key set:
for (TypeValue name: this.example.values()) {
System.out.println(name);
}
The code you give wouldn't even compile, which may be worth mentioning in future questions - "doesn't seem to work" is a bit vague!
Worth mentioning Java 8 approach, using BiConsumer and lambda functions:
BiConsumer<TypeKey, TypeValue> consumer = (o1, o2) ->
System.out.println(o1 + ", " + o2);
example.forEach(consumer);
Assuming that you've overridden toString method of the two types if needed.
Java 8 new feature forEach style
import java.util.HashMap;
public class PrintMap {
public static void main(String[] args) {
HashMap<String, Integer> example = new HashMap<>();
example.put("a", 1);
example.put("b", 2);
example.put("c", 3);
example.put("d", 5);
example.forEach((key, value) -> System.out.println(key + " : " + value));
// Output:
// a : 1
// b : 2
// c : 3
// d : 5
}
}
Useful to quickly print entries in a HashMap
System.out.println(Arrays.toString(map.entrySet().toArray()));
I did it using String map (if you're working with String Map).
for (Object obj : dados.entrySet()) {
Map.Entry<String, String> entry = (Map.Entry) obj;
System.out.print("Key: " + entry.getKey());
System.out.println(", Value: " + entry.getValue());
}
Using java 8 feature:
map.forEach((key, value) -> System.out.println(key + " : " + value));
Using Map.Entry you can print like this:
for(Map.Entry entry:map.entrySet())
{
System.out.print(entry.getKey() + " : " + entry.getValue());
}
Traditional way to get all keys and values from the map, you have to follow this sequence:
Convert HashMap to MapSet to get set of entries in Map with entryset() method.: Set dataset = map.entrySet();
Get the iterator of this set: Iterator it = dataset.iterator();
Get Map.Entry from the iterator: Map.Entry entry = it.next();
use getKey() and getValue() methods of the Map.Entry to retrive keys and values.
Set dataset = (Set) map.entrySet();
Iterator it = dataset.iterator();
while(it.hasNext()){
Map.Entry entry = mapIterator.next();
System.out.print(entry.getKey() + " : " + entry.getValue());
}
Print a Map using java 8
Map<Long, String> productIdAndTypeMapping = new LinkedHashMap<>();
productIdAndTypeMapping.forEach((k, v) -> log.info("Product Type Key: " + k + ": Value: " + v));
If the map holds a collection as value, the other answers require additional effort to convert them as strings, such as Arrays.deepToString(value.toArray()) (if its a map of list values), etc.
I faced these issues quite often and came across the generic function to print all objects using ObjectMappers. This is quite handy at all the places, especially during experimenting things, and I would recommend you to choose this way.
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public static String convertObjectAsString(Object object) {
String s = "";
ObjectMapper om = new ObjectMapper();
try {
om.enable(SerializationFeature.INDENT_OUTPUT);
s = om.writeValueAsString(object);
} catch (Exception e) {
log.error("error converting object to string - " + e);
}
return s;
}
You can use Entry class to read HashMap easily.
for(Map.Entry<TypeKey, TypeKey> temp : example.entrySet()){
System.out.println(temp.getValue()); // Or something as per temp defination. can be used
}