새소식

Java

Map 출력방법 정리

  • -

Iterator는 기억에 박혀있는데 두개는 뭔가 생각이 잘 안나서 리마인드용


public class PrintMap {
public static void main(String[] args) {
HashMap<String, Integer> hm = new HashMap<>();
hm.put("one", 1);
hm.put("two", 2);
hm.put("three", 3);
hm.put("four", 4);
hm.put("five", 5);
hm.put("six", 6);
hm.put("seven", 7);
hm.put("eight", 8);
hm.put("nine", 9);
hm.put("ten", 10);
//1. EntrySet
for(Entry<String, Integer> entrySet : hm.entrySet()) {
System.out.println(entrySet.getKey()+":"+entrySet.getValue());
}
System.out.println("----------------------------------------------");
//2. KeySet
for(String key : hm.keySet()) {
System.out.println(key+":"+hm.get(key));
}
System.out.println("----------------------------------------------");
//3. Iterator
Iterator<String> it = hm.keySet().iterator();
while(it.hasNext()) {
String nextKey = it.next();
System.out.println(nextKey+":"+hm.get(nextKey));
}
//2021-11 추가
hm.forEach((K,V) -> { System.out.println("KEY: "+K+", VALUE: "+V); });
}
}
view raw PrintMap.java hosted with ❤ by GitHub

맵은 순서보장이 안된다는걸 알고는 있었는데

돌려보면서 신기한게 3개의 출력순서는 동일하다...

함 찾아봐야지

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.