getOrDefault
- 찾는 키가 존재한다면 찾는 키의 값을 반환하고 없다면 기본 값을 반환하는 메서드
사용 방법
getOrDefault(Object key, V DefaultValue)
매개 변수 : 이 메서드는 두 개의 매개 변수를 허용합니다.
- key : 값을 가져와야 하는 요소의 키입니다.
- defaultValue : 지정된 키로 매핑된 값이 없는 경우 반환되어야 하는 기본값입니다.
반환 값 : 찾는 key가 존재하면 해당 key에 매핑되어 있는 값을 반환하고, 그렇지 않으면 디폴트 값이 반환됩니다.
다음은 getOrDefault 메서드의 사용법입니다.
import java.util.HashMap;
public class MapGetOrDefaultEx {
public static void main(String arg[]) {
String [] alphabet = { "A", "B", "C" ,"A"};
HashMap<String, Integer> hm = new HashMap<>();
for(String key : alphabet) hm.put(key, hm.getOrDefault(key, 0) + 1);
System.out.println("결과 : " + hm);
// 결과 : {A=2, B=1, C=1}
}
}
HashMap의 경우 동일 키 값을 추가할 경우 Value의 값이 덮어쓰기가 됩니다. 따라서 기존 key 값의 value를 계속 사용하고 싶을 경우 getOrDefault 메서드를 사용하여 위의 예와 같이 사용할 수 있습니다.
문제
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Read N and M
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int answer = 0;
// Map to store the courses and the list of student IDs with their attendance count
Map<String, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
// Read the number of students in the i-th course
int k = Integer.parseInt(br.readLine());
// Read the student IDs for the i-th course
st = new StringTokenizer(br.readLine());
for (int j = 0; j < k; j++) {
String studentId = st.nextToken();
map.put(studentId, map.getOrDefault(studentId, 0) +1);
}
}
for (int count : map.values()) {
if (count >= m) {
answer++;
}
}
// Output the result
System.out.println(answer);
br.close();
}
}
728x90
'Study > 코딩스터디_TIL' 카테고리의 다른 글
[JAVA 스터디] BufferedReader / BufferedWriter (0) | 2025.01.23 |
---|---|
[JAVA 스터디] 250122 Map 객체 활용 (1) | 2025.01.22 |
[JAVA 스터디] 250121 해시 알고리즘 (0) | 2025.01.21 |
[JAVA 스터디] 250120 hash 함수 (1) | 2025.01.20 |
[JAVA 스터디] 250116 BufferedReader (1) | 2025.01.16 |