Map에서 값을 가져오는 방법들
1. get()
map에서 가장 기본적으로 값을 조회할 때 사용하는 메소드
map에 key가 존재하면 해당하는 key의 value 값을 반환하고, 찾는 key가 없거나 null이면 null을 반환
public class Main {
public static void main(String[] args)throws Exception {
Map<Integer, Integer> map = new HashMap<>();
map.put(1, "nickname");
map.put(2, "helloworld");
map.put(3, "heesue");
map.get(1);
map.get(2);
map.get(3);
map.get(4);
}
}
2.getOrDefault()
map 내에 key 값이 없을 때, null 대신 기본값을 반환하도록 하는 메소드
key가 존재하면 key의 value를 반환하고, 없거나 null이면 deafultValue를 반환한다
HashMap의 경우 동일 키 값을 추가할 경우 value의 값이 덮어쓰기가 되기 때문에, 기존 key 값의 value를 계속 사용하고 싶을 경우에도 사용할 수 있다
public class Main {
public static void main(String[] args)throws Exception {
Map<Integer, Integer> map = new HashMap<>();
map.put(1, "nickname");
map.put(2, "helloworld");
map.put(3, "heesue");
map.getOrDefault(1, "default");
map.getOrDefault(2, "default");
map.getOrDefault(3, "default");
map.getOrDefault(4, "default");
}
}
3.Optional.ofNullable().orElse()
null 대신 기본 값을 반환하도록 할 수 있는 방법
Optional 객체를 활용한다
public class Main {
public static void main(String[] args)throws Exception {
Map<Integer, Integer> map = new HashMap<>();
map.put(1, "nickname");
map.put(2, "helloworld");
map.put(3, "heesue");
Optional.ofNullable(map.get(1)).orElse("default");
Optional.ofNullable(map.get(2)).orElse("default");
Optional.ofNullable(map.get(3)).orElse("default");
Optional.ofNullable(map.get(4)).orElse("default");
}
}
내용 좋아서 보면서 공부했습니다! 근데 각 예제에서
Map<Integer, Integer> map = new HashMap<>();는
Map<Integer, String> map = new HashMap<>(); 이죠??