Table of Contents
How?
Suppose you are solving a graph problem where you have been given a 2D array of edges and you need to find the shortest path between a source and a destination node. At this point, you could create a graph from the given edges.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
... public List<Integer> findShortestPath(int[][] edges, int src, int destination){ Map<Integer, List<Integer>> graph = new HashMap<>(); for(int[] edge: edges){ this.addEdge(graph, edge[0], edge[1]); //Let's say the graph is bidirectional this.addEdge(graph, edge[1], edge[0]); } //some more code } private void addEdge(Map<Integer, List<Integer>> graph, int a, int b){ //get the list of neighbors of node a List<Integer> listA = graph.getOrDefault(a, new ArrayList<>()); //add node b in the list listA.add(b); graph.put(a, listA); } //some more methods ... |
or you can write the same code using Map.computeIfAbsent method
1 2 3 4 5 6 7 8 9 10 11 |
... public List<Integer> findShortestPath(int[][] edges, int src, int destination){ Map<Integer, List<Integer>> graph = new HashMap<>(); for(int[] edge: edges){ graph.computeIfAbsent(edge[0], k->new ArrayList()).add(edge[1]); graph.computeIfAbsent(edge[1], k->new ArrayList()).add(edge[0]); } //some more code } //some more methods ... |
Cool??
Method Signature
1 |
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) |
Behaviour
- First, it checks if the key is present in the map. If the key is present, and a non-null value is related to the key, then it returns that value.
- If the key isn’t present in the map, or the null value is related to the key, then it attempts to compute the value using the given mappingFunction. It also enters the calculated value into the map unless the calculated value is null.
- If the mappingFunction returns null, the map records no mapping
- If the mappingFunction throws an unchecked exception, then the exception is re-thrown, and the map records no mapping
Test Your Knowledge
Seems like you got it, okay, so what would happen if try to do something like this (not sure why would you do it):
1 2 |
Map<Integer, Integer> map = new HashMap<>(); map.computeIfAbsent(1, k-> null).toString(); |
Hint: NPE