HashMap은 파이썬의 딕셔너리 같은 형태로 특정자료형에서 특정 자료형으로 맵핑되어 있는 자료구조이다.
예를들어,
HashMap<String, Integer이라고 한다면영희에서17로 맵핑할 수 있다.
여기서key = 영희value = 17이 되는 것이다.
하지만 HashMap은 key-value의 순서를 보장하지 않기 때문에 정렬을 할 수가 없다. 그렇지만, Key Set과 Entry Set을 얻어와서 이것을 정렬하는 방식으로 할 수 있다.
List<String> keySet = new ArrayList<>(map.keySet());
// 키 값으로 오름차순 정렬
Collections.sort(keySet);
List<Map.Entry<String, Integer>> entryList = new ArrayList<>(total_play_info.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) {
return entry2.getValue() - entry1.getValue();
}
});
가. 익명 클래스
new ~<>() { method }
위와 같이 객체 선언 뒤, {} 사이에 메서드를 구현할 수 있다.
예를들어, HashMap 객체를 선언하고
{map.put(~)}하면 바로 넣어진다.
그렇지만 코드가 무거워져 추천하지 않는 방식이락 한다.