Computer Science

HashMap 정렬

IamToday 2019. 5. 3. 20:01

Collections.sort 를 이용한다. 고유 인덱스를 유지하면서 정렬을 하고 싶을 때 사용한다. 

DB관리 할 때 사용할 수 있다. 

 

HashMap<Integer, Integer> hash= new HashMap<>();

 

...hash.put(0, 1);

 

Iterator it = sortHash(hash) //정렬된 결과를 탐색할 수 있도록 iterator를 반환한다. 

 


 

List<Integer> sortHash(final Map<Integer, Integer> map) {

    List<Integer> list = new ArrayList<>();

    

    list.addAll(map.keySet());

    

    Collections.sort(list, new Comparator<Object>() {

    

        @override

        public int compare(Object o1, Objecct o2) {

            Object v1 = list.get(o1);

            Object v2 = list.get(o2);

        

            return ((Comparable<Object>)v1).compareTo(v2);

        }

    });

    return list;

}