What are the four ways to traverse ConcurrentHashMap in Java
This article is to share with you about the four ways of traversing ConcurrentHashMap in Java. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article. Let's take a look at it.
Method 1: use entries in the for-each loop to traverse
System.out.println ("method 1: use entries to traverse in a for-each loop")
For (Map.Entry entry: map.entrySet ()) {
System.out.println ("Key =" + entry.getKey () + ", Value =" + entry.getValue ())
}
Method 2: traverse keys or values in the for-each loop, which is suitable for situations where values or keys are needed. Method 2 is 10% faster than method 1.
System.out.println ("method 2: traversing keys or values in a for-each loop, which is suitable for situations where a value or key is required"); / / traversing key for (String key: map.keySet ()) {System.out.println ("key =" + key);} / / traversing value for (String value: map.values ()) {System.out.println ("value =" + value);}
Method 3: use Iterator traversal, use concurrent collections to report no exceptions, and the performance is similar to method 2.
/ / use generic Iterator entries = map.entrySet () .iterator (); System.out.println ("use Iterator traversal and use generics:")
While (entries.hasNext ()) {Map.Entry entry = entries.next ()
System.out.println ("Key =" + entry.getKey () + ", Value =" + entry.getValue ()); / / Note that the collection is manipulated here, and the traversal below will not print 0 again.
If ("0" .equals (entry.getKey () {map.remove (entry.getKey ())
}
}
/ / do not use generics
Iterator entrys = map.entrySet () .iterator ()
System.out.println ("use Iterator traversal and do not use generics")
While (entrys.hasNext) {Map.Entry entry = (Map.Entry) entrys.next ()
String key = (String) entry.getKey ()
String value = (String) entry.getValue ()
System.out.println ("Key =" + key + ", Value =" + value)
}
Method 4: traversing by finding values through keys, this method is quite inefficient and is not recommended.
System.out.println ("Mode 4: traversing values through keys")
For (String key: map.keySet ()) {String value = map.get (key)
System.out.println ("Key =" + key + ", Value =" + value)
}
}
These are the four ways to traverse ConcurrentHashMap in Java. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.