본문 바로가기

Programming/Java & JSP & Spring

[Java] HashMap 사용법과 정렬

HashMap이란?

HashMap이란 Map인터페이스의 한 종류로써 Key와 Value 값으로 데이터를 저장하는 형태를 가지고 있다.

쉽게 말해 Key, Value 값으로 저장하는 List 형태의 조상이라고 생각하시면 됩니다.


Map에 종류에는 Hashtable, HashMap, LinkedHashMap, SortedMap, TreeMap 등이 있다.

이들 객체 또한 Key, Value로 데이터를 저장하게 된다.


HashMap 또한 Map인터페이스를 구현한 것이기 때문에 Map의 속성을 모두 가지고 있고, 저장 방식 또한

동일하다. 그리고 해싱(Hashing)이란 검색 방법을 사용하기 때문에 많은 양의 데이터를 검색하는데

있어서 뛰어난 성능을 보여준다.


HashMap에서 한가지 주의 하실 점이 Map에 데이터를 등록할 때, Key값은 중복이 되지 않고

Value값은 중복이 허용된다는 점이다.


즉, 이 말은 Key값을 수정하기 위해서는 덮어쓰면 된다라는 뜻이다.


HashMap 정렬

Key에 의한 정렬

  • TreeMap을 사용한다. 
    TreeMap 은 중복을 허용하지 않고 Key 값을 기준으로 정렬을 해주는 자료구조이다.
    (HashMap 은 내부 hash 값에 따라 키순서가 정해지므로 특정 규칙없이 출력된다.)
  • 역 정렬 또한 가능하다.


Sample code

//메인메소드에서 구현

Map<Double,Integer> hashMap = new HashMap<Double,Integer>();

hashMap.put(1.1,99);

hashMap.put(2.2,70);

hashMap.put(13.3,89);

hashMap.put(7.7,79);

hashMap.put(10.1,99);


TreeMap<Double,Integer> tm = new TreeMap<Double,Integer>(hashMap);

 

Iterator<Double> iteratorKey = tm.keySet( ).iterator( );   //키값 오름차순 정렬(기본)


while(iteratorKey.hasNext()) {

Double key = iteratorKey.next();

System.out.println(key+","+tm.get(key));

}


Value에 의한 정렬 

  • comparator을 직접 구현하여 정렬 할 수 있다.

  • 아래 코드는 key 목록을 리스트에 담고, 해당 리스트를 value를 기준으로 정렬하는 방식으로 구현되어었다.


Sample code

//메인메소드에서 구현

Map<String,Integer> map = new HashMap<String,Integer>();


map.put("a",3);

map.put("b",12);

map.put("c",54);

map.put("d",51);

map.put("e",8);

         

System.out.println("------------sort 전 -------------");

Iterator iterator = map.keySet().iterator();


while(iterator.hasNext {

String temp = (String) iterator.next();

System.out.println(temp + " = " + map.get(temp));

}


Iterator it = sortByValue(map).iterator();


System.out.println("------------sort 후 -------------");


while(it.hasNext()) {

String temp = (String) it.next();

System.out.println(temp + " = " + map.get(temp));

}


//별도의 스태틱 함수로 구현

public static List sortByValue(final Map map) {

List<String> list = new ArrayList();

list.addAll(map.keySet());


Collections.sort(list,new Comparator() {

public int compare(Object o1,Object o2) {

Object v1 = map.get(o1);

Object v2 = map.get(o2);


return ((Comparable) v2).compareTo(v1);

}

});


Collections.reverse(list); // 주석시 오름차순

return list;

}







출처 : http://ithub.tistory.com/34