Calculating Java 8 map with given value

My map looks like this

private Map<String, LinkedHashSet<String>> map = new HashMap<>();

      

in traditional approach i can add value for card with key validation like below

public void addEdge(String node1, String node2) {
        LinkedHashSet<String> adjacent = map.get(node1);
        if (adjacent == null) {
            adjacent = new LinkedHashSet();
            map.put(node1, adjacent);
        }
        adjacent.add(node2);
    }

      

with java 8, I can do something like this, with this I get the same output too.

map.compute(node1, (k,v)-> {
            if(v==null) {
                v=new LinkedHashSet<>();
            }
            v.add(node2);
            return v;
            });

      

Is there a better way to do this with java 8?

+3


source to share


1 answer


Using

map.computeIfAbsent(node1, k -> new LinkedHashSet<>()).add(node2);

      

If node1

already found on the map, it will be equivalent to:

map.get(node1).add(node2);

      



If node1

not already on the map, it will be equivalent to:

map.put(node1, new LinkedHashSet<>()).add(node2);

      

This is exactly what you are looking for and is even described as a use case in the documentation .

+3


source







All Articles