본문 바로가기

JAVA

[JAVA] HashMap 기본 및 정렬

HashMap

: HashMap은 Key, Value 한 쌍을 데이터 타입으로 가진다. 키를 해싱하여 자료를 저장하고 꺼내오기 때문에 속도가 빠르다.

HashMap<String, Integer> hashMap = new HashMap<>();

hashMap.put("사과", 1); //쓰기
System.out.println(hashMap.get("사과")); //읽기


//전체 순회
for(Map.Entry<String, Integer> entry : hashMap.entrySet()){
	entry.getKey();
    entry.getValue();
}

//key 값이 있는지 검사, 있으면 true 없으면 false
hashMap.containsKey("사과")

//HashMap 크기
hashMap.size()

같은 key로 value를 입력할 때에는 이전 키, value를 지금의 것으로 업데이트한다.

 

HashMap 정렬

HashMap을 Key값 기준으로 정렬할 때는 TreeMap을 활용할 수 있다.

HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 34);
map.put("Cat", 26);
map.put("Banana", 27);
map.put("Dog", 29);

Map<String, Integer> sortedMap = new TreeMap<>(map);
System.out.println(sortedMap); //{Apple=34, Banana=27, Cat=26, Dog=29}

Value값 기준으로 정렬 시 comparator을 활용할 수 있다.

HashMap<String, Integer> map = new HashMap<>();
map.put("a", 3);
map.put("b", 2);
map.put("c", 1);
List<Map.Entry<String, Integer>> entryList = new LinkedList<>(map.entrySet());
//오름차순 정렬
entryList.sort(((o1, o2) -> map.get(o1.getKey()) - map.get(o2.getKey())));

//내림차순 정렬
//entryList.sort(((o1, o2) -> map.get(o2.getKey()) - map.get(o1-getKey())));

for(Map.Entry<String, Integer> entry : entryList){
    System.out.println("key : " + entry.getKey() + ", value : " + entry.getValue());
}

//key : c, value : 1
//key : b, value : 2
//key : a, value : 3

'JAVA' 카테고리의 다른 글

배열 복사 (얕은 복사, 깊은 복사)  (0) 2023.02.06
[Java] substring (문자열 자르기)  (2) 2023.01.21
[Java] BigInteger(큰 정수)  (0) 2023.01.18
[JAVA] 객체지향(3)  (0) 2022.01.30
[JAVA] 객체지향 (2)  (0) 2022.01.24