How to Iterate Over a Map in Java
Map
in Java. Lets go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement Map
interface, following techniques will work for any map implementation ( HashMap
, TreeMap
, LinkedHashMap
, Hashtable
, etc.) Method #1: Iterating over entries using For-Each loop.
This is the most common method and is preferable in most cases. 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 For-Each loop was introduced in Java 5 so this method is working only in newer versions of the language. Also 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 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 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 performance point of view this method is equal to 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.
Method 1: / 출력 맵 의 키 쌍
Map
for(Map.Entry
System.out.println("Key=" + entry.getKey() + ", Value = " + entry.getValue());
}
Method 2: / / 맵 의 키 나 값 만 있 으 면 이 방법 을 사용 합 니 다.
Map
//Iterating over keys only
for(String key:map.keySet()){
System.out.println("Key="+key);
}
//Iterating over values only
for(String value:map.values()){
System.out.println("Value="+value);
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.