다른 사람이 짠 알고리즘이나 자바 코드를 보면 HashSet이나 HashMap이 심심찮게 보였다. 그럴때마다 이해하지 못했고 다른 방식으로 넘어갔던 경험이 있다. 이번에야 말로 확실하게 정리하고 넘어가야겠다.
HashSet내의 요소들은 순서를 가지지 않으며, 중복된 값을 허용하지 않는다.
// HashSet 객체 생성
Set<String> set = new HashSet<>();
// 요소 추가
set.add("Apple");
set.add("Banana");
set.add("Cherry");
set.add("Apple"); // 중복된 요소는 추가되지 않음
// 요소 개수 출력
System.out.println("Set size: " + set.size());
// 모든 요소 출력
for (String element : set) {
System.out.println(element);
}
// 요소 삭제
set.remove("Banana");
// 요소 포함 여부 확인 (존재하면 true)
boolean contains = set.contains("Cherry");
System.out.println("Set contains Cherry? " + contains);
// Set 비우기
set.clear();
// 비어있는 Set 확인
boolean empty = set.isEmpty();
System.out.println("Set is empty? " + empty);
public class UniqueNumbers {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5, 2, 4, 6, 7, 1, 3};
// HashSet 객체 생성
Set<Integer> uniqueNumbers = new HashSet<>();
// 중복되지 않은 숫자들을 HashSet에 추가
for (int number : numbers) {
uniqueNumbers.add(number);
}
// 중복되지 않은 숫자들 출력
System.out.println("Unique numbers:");
for (int number : uniqueNumbers) {
System.out.println(number);
}
}
}
Map API는 key-value 쌍을 저장하는 자료구조를 구현하는데 사용된다. Map은 인터페이스 이며, 그 구현체로는 HashMap, TreeMap, LinkedHashMap 등이 있다. 각 키는 유일하며, 각 키에는 하나의 값이 매핑되어 있다.
HashMap을 사용하면 데이터의 검색에 용이하다.
put(K key, V value)
저장된 키에 지정된 값을 매핑한다. 이미 해당 키에 값이 매핑되어 있으면, 기놎 값이 새 값으로 대체된다.
get(Object key)
지정된 키에 매핑된 값을 반환단다. 키가 맵에 존재하지 않는 경우 null을 반환한다.
remove(Object key)
지정된 키와 그에 매핑된 값을 맵에서 제거한다.
containsKey(Object key)
맵이 지정된 키를 포함하고 있는지 여부를 반환한다.
containsValue(Object value)
맵이 하나 이상의 키에 지정된 값을 매핑하고 있는지 여부를 반환한다.
keySet()
맵의 모든 키를 Set형태로 반환한다.
values()
맵의 모든 값을 Collection 형태로 반환한다.
entrySet()
맵의 모든 매핑을 키-값 쌍의 형태인 Map.Entry 객체로 포함하는 Set을 반환한다.
//Key-Value를 관리하는 Map 객체생성
Map<String, Integer> studentScores = new HashMap<>();
// 데이터 추가
studentScores.put("Kim", 95);
studentScores.put("Lee", 85);
studentScores.put("Park", 90);
studentScores.put("Choi", 80);
// 데이터 조회
System.out.println("Kim's score: " + studentScores.get("Kim"));
System.out.println("Lee's score: " + studentScores.get("Lee"));
// 데이터 수정
studentScores.put("Park", 92);
System.out.println("Park's score after update: " + studentScores.get("Park"));
// 데이터 삭제
studentScores.remove("Choi");
System.out.println("Choi's score after removal: " + studentScores.get("Choi"));
// 전체 데이터 출력
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
System.out.println(entry.getKey() + "'s score: " + entry.getValue());
}
public static void main(String[] args) {
String str = "Hello, World!";
HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
char[] strArray = str.toCharArray();
for (char c : strArray) {
//charCountMap의 HashMap에 c인덱스 값의 key가 있는가?
if (charCountMap.containsKey(c)) {
//있다면 원래 있는 key값의 value값에 +1 한다
charCountMap.put(c, charCountMap.get(c) + 1);
} else {
//없다면 c인덱스 값을 넣고 value는 1 대입
charCountMap.put(c, 1);
}
}
System.out.println("Character Counts:");
//key만 빼내서 c에 대입
for (char c : charCountMap.keySet()) {
System.out.println(c + ": " + charCountMap.get(c));
}
}