[JAVA] HashMap, HashSet, TreeMap사용 방법
2023. 12. 2. 15:12ㆍJAVA
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);
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);
}
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.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<>();
// 요소 추가
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Orange");
hashSet.add("Apple");
System.out.println("HashSet의 크기: " + hashSet.size());
System.out.println("HashSet의 요소:");
for (String fruit : hashSet) {
System.out.println(fruit);
}
}
}
HashSet의 크기: 3
HashSet의 요소:
Apple
Orange
Banana
TreeMap 이란
TreeSet은 SortedSet 인터페이스를 구현한 클래스로, 요소들을 자동으로 정렬하고 중복을 제거하여 저장한다.
TreeMap 사용법
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Orange");
treeSet.add("Apple"); // 중복된 요소는 무시됨
System.out.println("TreeSet의 크기: " + treeSet.size());
System.out.println("TreeSet의 요소:");
for (String fruit : treeSet) {
System.out.println(fruit);
}
}
}
'JAVA' 카테고리의 다른 글
[JAVA] 배열, ArrayList 내림차순, 오름차순 정렬 (0) | 2023.12.10 |
---|---|
[JAVA] 특정 문자열 제거하기, 연속된 문자열 (0) | 2023.11.12 |
[JAVA] Array, List, ArrayList 개념 정리 (0) | 2023.10.23 |
[JAVA] 약수 구하기 (0) | 2023.10.23 |