Hyunebee

Set, Map 본문

Java/Java의 정석

Set, Map

Hyunebee 2022. 3. 8. 18:45

HashSet

Set인터페이스를 구현 Set의 대표적인 특징처럼 중복된 요소를 저장하지 않는다.  그리고 순서를 보장하지 않기 때문에 저장 순서를 유지하고자 한다면 LinkedHashSet을 사용한다. 

 

TreeSet

TreeSet은 이진 검색 트리라는 자료구조의 형태로 데이터를 저장하는 컬렉션 클래스이다. 

이진 검색 트리는 정렬, 검색, 범위 검색에 높은 성능을 보이는 자료 구조이다. 지금은 더 향상된 레드-블랙 트리로 구현되어 있다. 이또한 Set인터페이스를 구현 중복된 요소를 저장하지 않고 순서를 보장하지 않는다.  

 

https://ko.wikipedia.org/wiki/%EC%9D%B4%EC%A7%84_%ED%83%90%EC%83%89_%ED%8A%B8%EB%A6%AC

이진 검색트리의 노드는 

class TreeNode{
    TreeNode left;
    TreeNode right;
    Object element;
}

왼쪽 오른쪽 자식 노드와 객체를 저장하기위한 변수로 구성된다.

 

 

HashMap

HashMap또한 Key, Value형태를 데이터로 저장한다는 특징을 가지고 있다. 그리고 Hash를 이용하기 때문에 검색속도가 매우빠르다. 

HashMap은 Key와 Value를 Object형태로 저장한다. 해싱을 사용한 저장은 순서를 보장하지 않는다

 

 

TreeMap

import java.util.*;

class TreeMapEx1 {
    public static void main(String[] args) {
        String[] data = { "A","K","A","K","D","K","A","K","K","K","Z","D" };

        TreeMap map = new TreeMap();

        //Key값과 Value값을 생성
        for(int i=0; i < data.length; i++) {
            if(map.containsKey(data[i])) {
                Integer value = (Integer)map.get(data[i]);
                map.put(data[i], value.intValue() + 1);
            } else {
                map.put(data[i], 1);
            }
        }

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

        System.out.println("= 기본정렬 =");
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            int value = ((Integer)entry.getValue()).intValue(); // 데이터에서 value꺼내고 int값으로 사용
            System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value );
        }
        System.out.println();

        // map을 ArrayList로 변환한 다음에 Collectons.sort()로 정렬
        Set set = map.entrySet(); // key value형태를 Set으로 만들어줌
        List list = new ArrayList(set);    // ArrayList(Collection c) // ArrayList형식으로 변경

        // static void sort(List list, Comparator c)
        Collections.sort(list, new ValueComparator());// 값으로 정렬하기 위해서 기용

        it = list.iterator();

        System.out.println("= 값의 크기가 큰 순서로 정렬 =");
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            int value = ((Integer)entry.getValue()).intValue();
            System.out.println(entry.getKey() + " : " + printBar('#', value) + " " + value );
        }

    } //   public static void main(String[] args)

    static class ValueComparator implements Comparator {
        public int compare(Object o1, Object o2) {
            if(o1 instanceof Map.Entry && o2 instanceof Map.Entry) {
                Map.Entry e1 = (Map.Entry)o1;
                Map.Entry e2 = (Map.Entry)o2;

                int v1 = ((Integer)e1.getValue()).intValue();
                int v2 = ((Integer)e2.getValue()).intValue();

                return  v2 - v1;
            }
            return -1;
        }
    }  //     static class ValueComparator implements Comparator {

    public static String printBar(char ch, int value) {
        char[] bar = new char[value];

        for(int i=0; i < bar.length; i++) {
            bar[i] = ch;
        }

        return new String(bar);
    }
}

'Java > Java의 정석' 카테고리의 다른 글

Enum  (0) 2022.03.12
제네릭스(Generics)  (0) 2022.03.09
Arrays  (0) 2022.03.07
Stack, Queue  (0) 2022.03.07
Collection Framework  (0) 2022.03.06