JAVA
Map - getOrDefault(), putIfAbsent() in Java
seoca
2019. 7. 23. 06:12
Map - getOrDefault(key, Default-value)
If the key is already mapped with a specified value, return the value, or return the default value if no value is associated with any key.
특정 key가 특정 value와 map 되어있다면 해당 value를 리턴하고 map이 안되어 있을 경우 default value를 리턴한다.
Example code
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] fruit = {"apple", "banana", "apple", "grape"};
Map<String, Integer> map = new HashMap<>();
for(String a : fruit) map.put(a, map.getOrDefault(a, 0) + 1);
System.out.println(map); //{banana=1, apple=2, grape=1}
}
}
|
apple is duplicated, that's why the value is '2'.
HashMap 은 중복허용을 하지 않으니 같은 key인 apple은 2가 될 수 밖에 없다.
putIfAbsent
The key is accepted if the key isn't associated with any value.
key가 특정한 value와 mapping 되어 있지 않을때만 map이 된다.
Example code
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap<String , String> map = new HashMap<>();
map.putIfAbsent("key","apple");
map.putIfAbsent("key","grape");
System.out.println(map); //{key=apple}
HashMap<String , String> map2 = new HashMap<>();
map2.putIfAbsent("key","grape");
map2.putIfAbsent("key","apple");
System.out.println(map2); //{key=grape}
}
}
|