본문 바로가기

개발일지/Java

computeIfAbsent

Before

 Map<Integer, List<Integer>> graph = new HashMap<>();
 
 
for (int i = 0; i < n; i++) {
    if(graph.get(arr[i]) == null) {
    	graph.put(arr[i], new LinkedList<>()); 
    } 
    
    graph.get(arr[i]).add(i);
}

 

After

Map<Integer, List<Integer>> graph = new HashMap<>();
 
for (int i = 0; i < n; i++) {
    graph.computeIfAbsent(arr[i], v -> new LinkedList<>()).add(i);
}