[JAVA] HashMap, HashSet, TreeMap, TreeSet 사용 방법

2023. 12. 2. 15:12JAVA

 

Hash

 

HashMap 이란

 

HashMap은 Map 인터페이스의 구현체중 하나이다. 특징으로는 Key, Value 형태로 값을 저장한다. Key 값은 고유 값으로 저장된다는 특징을 가지고 있다. Key, Value 한 세트씩 하나의 노드 형태로 저장되는데 이를 통해 Key 값을 이용해 빠르게 Value 값을 찾을 수 있다

 

HashMap 사용법

 

import java.util.*;
import java.lang.*;
import java.io.*;

class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> hashmap = new HashMap<>();
        HashMap<String, ArrayList<Integer>> hashmapList = new HashMap<>();

        hashmap.put("A", 1);
        hashmap.put("B", 2);
        hashmap.put("C", 3);

        System.out.println(hashmap);

        int value_1 = hashmap.get("A");
        System.out.println(value_1);

        hashmap.remove("A");

        boolean containA = hashmap.containsKey("A");
        System.out.println(containA);

        Integer getValue_1 = hashmap.getOrDefault("A", 0);
        Integer getValue_2 = hashmap.getOrDefault("B", 0);
        System.out.println(getValue_1);
        System.out.println(getValue_2);

        for (String key : hashmap.keySet()) {

            int value = hashmap.get(key);
            System.out.println("Key: " + key + ", Value: " + value);
            
        }

        System.out.println("-----------");
        hashmapList.put("A", new ArrayList<>());
        hashmapList.put("B", new ArrayList<>());
        hashmapList.put("C", new ArrayList<>());

        hashmapList.get("A").add(1);
        hashmapList.get("A").add(2);
        hashmapList.get("B").add(3);
        hashmapList.get("C").add(4);
        hashmapList.get("C").add(5);
        hashmapList.get("C").add(6);

        System.out.println(hashmapList.getOrDefault("C", new ArrayList<>()));
        System.out.println(hashmapList.getOrDefault("D", new ArrayList<>()));
        System.out.println(hashmapList.getOrDefault("C", new ArrayList<>()).size());
        System.out.println(hashmapList.getOrDefault("D", new ArrayList<>()).size());

        for (String key : hashmapList.keySet()) {

            System.out.println("Key: " + key + ", Value: " + hashmapList.get(key));
            
        }
        
    }
}

 

HashSet 이란

 

HashSet은 자바 컬렉션 프레임워크의 일부로, 중복을 허용하지 않고 순서가 없는 요소들을 저장하는데 사용한다. 종종 코딩테스트에서 중복값 제거한 리스트를 만들때 사용한다.

 

HashSet 사용법

 

import java.util.*;
import java.lang.*;
import java.io.*;

class Main {
    public static void main(String[] args) {
        HashSet<String> fruits = new HashSet<>();

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");
        fruits.add("Apple");

        for (String val : fruits) {
            System.out.println(val);
        }

        System.out.println(fruits.contains("Apple"));

        fruits.remove("Apple");

        System.out.println(fruits.contains("Apple"));

        fruits.clear();

        System.out.println("-----------");
        HashSet<String> new_fruits = new HashSet<>(Arrays.asList("Apple", "Banana", "Orange"));

        for (String val : new_fruits) {
            System.out.println(val);
        }

        System.out.println("-----------");       
        Iterator iter = new_fruits.iterator();

        //hasNext() 가져올게 있다면 true : false 
        while (iter.hasNext()) {
            System.out.println(iter.next());
        }
        
    }
}

 

TreeMap

 

이진트리 형태 구조 Map Key, Value 형태로 기본 HashMap에 비하면 느리지만 올림차순 정렬과 1:1 매핑을 보장한다.

 

TreeMap 사용법

 

import java.util.*;
import java.util.Map.*;
import java.lang.*;
import java.io.*;

class Main {
    public static void main(String[] args) {
        TreeMap<Integer, String> fruits = new TreeMap<>();

        fruits.put(1, "Apple");
        fruits.put(2, "Peach");
        fruits.put(3, "Orange");
        fruits.put(1, "Banana");

        System.out.println(fruits);
        System.out.println(fruits.get(1));
        System.out.println(fruits.firstEntry());
        System.out.println(fruits.firstKey());
        System.out.println(fruits.lastEntry());
        System.out.println(fruits.lastKey());

        System.out.println("---------");
        for (Entry<Integer, String> val : fruits.entrySet()) {
            System.out.println("key = " + val.getKey() + " value = " + val.getValue());
        }

        System.out.println("---------");
        for(Integer val : fruits.keySet()) {
            System.out.println("key = " + val + " value = " + fruits.get(val));
        }

        System.out.println("---------");
        System.out.println(fruits.getOrDefault(1, "null"));
        System.out.println(fruits.getOrDefault(10, "null"));

        // 첫번째, 마지막 값 출력
        System.out.println("---------");
        System.out.println(fruits.firstEntry());
        System.out.println(fruits.firstEntry().getValue());
        System.out.println(fruits.lastEntry());
        System.out.println(fruits.lastEntry().getValue());

        // 크기 비교 후 기준 값에서 크고 작은 값 출력
        System.out.println("---------");
        System.out.println(fruits.higherEntry(2));
        System.out.println(fruits.lowerEntry(2));

        // 출력 후 삭제
        System.out.println("---------");
        System.out.println(fruits.pollFirstEntry());
        System.out.println(fruits.pollLastEntry());
        System.out.println(fruits);

        // 내림차순 정렬
        System.out.println("---------");
        fruits = new TreeMap<>(Comparator.reverseOrder());
        fruits.put(1, "Apple");
        fruits.put(2, "Peach");
        fruits.put(3, "Orange");
        System.out.println(fruits);
        
    }
}

 

TreeSet 이란

 

TreeSet은 SortedSet 인터페이스를 구현한 클래스로, 요소들을 자동으로 정렬하고 중복을 제거하여 저장한다.

 

TreeSet 사용법

 

import java.util.*;
import java.lang.*;
import java.io.*;

class Main {
    public static void main(String[] args) {
        TreeSet<Integer> scores = new TreeSet<>();
        
        scores.add(10);
        scores.add(30);
        scores.add(50);
        scores.add(70); 
        scores.add(90); 

        System.out.println(scores);
        
        for (Integer score : scores) {
            System.out.println(score);
        }

        System.out.println("-----------");
        System.out.println(scores.first());
        System.out.println(scores.last());

        System.out.println("-----------");
        System.out.println(scores.higher(50));
        System.out.println(scores.lower(30));

        System.out.println("-----------");
        System.out.println(scores.floor(55));

        System.out.println("-----------");
        System.out.println(scores.ceiling(55));

        System.out.println("-----------");
        System.out.println(scores.pollFirst());
        System.out.println(scores.pollLast());
        System.out.println(scores);

        System.out.println("-----------");
        scores = new TreeSet<>(Comparator.reverseOrder());
        scores.add(10);
        scores.add(30);
        scores.add(50);
        scores.add(70); 
        scores.add(90);
        System.out.println(scores);
        
    }
}