Search code examples
java-8

Java 8 map compute with set as value


My map looks like this

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

in traditional approach I can add value to map with key check as 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 one also I'm getting same output.

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

is there any better way to do with java 8?


Solution

  • Use

    // in Java 22+, you should name the "k" below as "_"
    map.computeIfAbsent(node1, k -> new LinkedHashSet<>()).add(node2);
    

    If node1 is already found in the map, it will be equivalent to:

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

    If node1 is not already in the map, it will be equivalent to:

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

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