Fall in IT.

Map 객체, key 또는 value를 사용한 정렬 본문

프로그래밍언어/Java

Map 객체, key 또는 value를 사용한 정렬

D.Y 2016. 4. 8. 00:40

안녕하세요. 오늘은 자바에서 Map객체를 정렬하는 방법에 대하여 알아보겠습니다.


Map은 기본적으로 key, value로 구성되어 있습니다. key에 의한 정렬과 value에 의한 정렬 두가지를 알아보도록 하겠습니다.




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;

    }


결과 출력




모두 즐거운 코딩하세요~




Comments