Get the App
SLTechnology News&Howtos  ›  Development  › 

How to get key and value of map in JAVA

Shulou Source: shulou.com Published: 2022-06-03 09:40:49 11月15日 Update

Editor to share with you how to get map key and value in JAVA, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

There are two ways to get the key and value of map:

Map.keySet (): first get the key of map, then get the corresponding value; map..entrySet () according to key: query the key and value of map at the same time, you only need to query it once.

When traversing key and value at the same time, the performance difference between keySet and entrySet depends on the specific conditions of key, such as complexity (complex objects), discreteness, conflict rate and so on. In other words, it depends on the cost of finding value by HashMap. EntrySet's operation of fetching all key and value at once has a performance overhead, and when this loss is less than the cost of finding value by HashMap, the performance advantage of entrySet will be reflected.

The keySet method is more appropriate when only traversing the key, because entrySet takes out the useless value, wasting performance and space.

When only traversing the value, the vlaues method is the best choice, and entrySet is slightly better than the keySet method.

Through the map.keySet () method

Method 1: get the value of key and then get value

For (String key: map.keySet ()) {String value = map.get (key); System.out.println (key+ "" + value);}

Method 2: use an iterator to get key

Iterator iter = map.keySet (). Iterator (); while (iter.hasNext ()) {String key=iter.next (); String value = map.get (key); System.out.println (key+ "" + value);}

Through the map.entrySet () method

Method 1: loop each key-value pair in map, and then get key and value

For (Entry vo: map.entrySet ()) {vo.getKey (); vo.getValue (); System.out.println (vo.getKey () + "+ vo.getValue ());}

Method 2: use an iterator to get key

Iterator iter = map.entrySet (). Iterator (); while (iter.hasNext ()) {Entry entry = iter.next (); String key = entry.getKey (); String value = entry.getValue (); System.out.println (key+ "" + value);}

The above is all the content of the article "how to get the key and value of map in JAVA". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Method performance article complexity content depends at the same time cost query iteration appropriate one-time not much advantage complexity most object difference form situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Technology Shulou Tech Info Microsoft MariaDB Redmi