HashMap | 값 가져오기 | 정렬하기 | TreeMap | etc
HashMap의 특징
- Key : Value 로 이루어진 자료형.
- Key는 고유한 값으로 중복이 허용되지 않는다. value는 중복이 가능하다.
- 순서가 없는 자료 구조.
메소드들
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "jina");
map.put(2, "dana");
map.put(3, "alex");
[ 키와 값을 같이 가져오는 entrySet() ]
키와 값을 같이 가져와야하는 경우, Map.Entry<k,v> 인터페이스의 entrySet() 메서드를 사용한다.
Map 객체의 키와 값을 접근할 수 있도록 해주는 getKey(), getValue() 함수가 존재한다.
방법 1: for문
for( Map.Entry<Integer,String> pair : map.entrySet() ){
System.out.println(pair.getKey(), pair.getValue());
}
/*
1, jina
2, dana
3, alex
*/
방법 2 : forEach()문
map.forEach((k,v) -> System.out.println(String.format("Key (name) is: %s, Value (age) is : %s", k, v)));
[ 키 가져오는 keySet() ]
for (String key : map.keySet()) {
System.out.println(key);
}
[ 값 가져오는 values() ]
for (String val : map.values()) {
System.out.println(val);
}
[ 특정 키가 존재하는지 확인하는 containsKey() ]
반환 값은 true, false
boolean result = map.containsKey("Jane");
[HashMap 정렬 방법]
1. List 활용
keySet() 또는 values()는 키와 값들을 리스트로 리턴한다.
1.1 key로만 정렬하는 경우
import java.util.Comparator;
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "jina");
map.put(2, "dana");
map.put(3, "alex");
List<Integer> keyList = new ArrayList<> (map.keySet());
keyList.sort((s1,s2) -> s1.compareTo(s2));
for(Integer key : keyList){
System.out.println(key, map.get(key));
}
}
}
keyList.sort(String::compareTo);로 대체 가능.
1.2 values로만 정렬하는 경우
import java.util.Comparator;
import java.util.Arrays;
public class Example {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "jina");
map.put(2, "dana");
map.put(3, "alex");
List<String> valList = new ArrayList<> (map.values());
valList.sort(String::compareTo);
for(String val : valList){
System.out.println(val);
}
}
}
2. TreeMap 활용
TreeMap에 객체를 저장하면 키가 자동으로 오름차순 정렬이 되기 때문에 추가나 삭제가 HashMap보다 오래 걸린다. (문자열일 경우 유니코드 정렬) TreeMap는 일반적으로 Map으로써 HashMap보다 성능이 떨어진다. 하지만 정렬된 상태로 Map을 유지해야 하거나 정렬된 데이터를 조회해야 하는 범위 검색이 필요한 경우 TreeMap을 사용하는 것이 효율성면에서 좋다.
import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;
public class Example {
public static void main(String[] args) {
Comparator<String> comparator = (s1, s2) -> s1.compareTo(s2);
Map<String, String> map = new TreeMap<>(comparator);
map.put("alex", "hi");
map.put("beyond", "hello");
map.put("carin", "New");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", "
+ "Value: " + entry.getValue());
}
}
}
key가 오름차순으로 정렬되어 출력된다. vlaue는 정렬하지 않기 때문에 key를 정렬하는 경우에만 사용한다.
TreeMap은 HashMap과 구조만 다르고 기본적인 Map 인터페이스를 같이 상속받고 있으므로 메소드의 사용법 자체는 HashMap과 동일하다.
[TreeMap 선언]
TreeMap<Integer,String> map = new TreeMap<>();
TreeMap<Integer,String> map2 = new TreeMap<Integer,String>(){{put(1,"a");}};
[TreeMap 추가]
map.put(1, "제니");
[TreeMap 삭제]
map.remove(인덱스); 맴의 인덱스에 해당하는 key값 제거
map.clear(); //모든 값 제거
[TreeMap 단일 값 출력]
TreeMap<Integer,String> map = new TreeMap<Integer,String>(){{//초기값 설정
put(1, "사과");
put(2, "복숭아");
put(3, "수박");}
};
System.out.println(map); //전체 출력 : {1=사과, 2=복숭아, 3=수박}
System.out.println(map.get(1));//key값 1의 value얻기 : 사과
System.out.println(map.firstEntry());//최소 Entry 출력 : 1=사과
System.out.println(map.firstKey());//최소 Key 출력 : 1
System.out.println(map.lastEntry());//최대 Entry 출력: 3=수박
System.out.println(map.lastKey());//최대 Key 출력 : 3
※ 참고
https://dev-coco.tistory.com/39
[Java] TreeMap
TreeMap이란? TreeMap은 이진트리를 기반으로 한 Map 컬렉션이다. 같은 Tree구조로 이루어진 TreeSet과의 차이점은 TreeSet은 그냥 값만 저장한다면, TreeMap은 키와 값이 저장된 Map, Entry를 저장한다는 점이
dev-coco.tistory.com
3. Stream 활용
import java.util.*;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("Nepal", "Kathmandu");
map.put("United States", "Washington");
map.put("India", "New Delhi");
map.put("England", "London");
map.put("Australia", "Canberra");
// sort by key
List<Map.Entry<String, String>> entries =
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toList());
for (Map.Entry<String, String> entry : entries) {
System.out.println("Key: " + entry.getKey() + ", "
+ "Value: " + entry.getValue());
}
// sort by value
System.out.println();
entries = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toList());
for (Map.Entry<String, String> entry : entries) {
System.out.println("Key: " + entry.getKey() + ", "
+ "Value: " + entry.getValue());
}
}
}