티스토리 뷰
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}
}
}
|
'JAVA' 카테고리의 다른 글
Collection framework - HashMap (0) | 2019.07.23 |
---|---|
keySet() in Java (0) | 2019.07.23 |
Java IOException - Stream Closed (0) | 2019.07.19 |
Error: could not find or load main class Main (0) | 2019.07.19 |
Serialization example code in java (0) | 2019.07.17 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- HackerRank Algorithm
- easy javascript algorithm
- hackerrank
- easy algorithm
- HashMap
- C++
- Javascript Algorithm
- code refactoring
- 알고리즘
- 프로그래머스 알고리즘
- spring boot application
- 프로그래머스 알고리즘문제
- algorithm
- math.max
- hackerrank solution
- Object type casting
- string class in java
- repeat()
- hackerrank javascript
- hackerrank javascript solution
- substring()
- javascript
- Collection Framework
- 프로그래머스
- java
- math.abs
- equals()
- rest parameter
- ... in Javascript
- compareTo()
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
글 보관함