Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 map compute with set as value

Tags:

java-8

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?

like image 591
Sudarsana Kasireddy Avatar asked Apr 02 '17 00:04

Sudarsana Kasireddy


People also ask

How do you set a value on a map?

The map. set() method is used to add key-value pairs to a Map object. It can also be used to update the value of an existing key. Each value must have a unique key so that they get mapped correctly.

How do you get a specific value from a map?

HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

What does the computeIfAbsent () method on map do?

The computeIfAbsent(Key, Function) method of HashMap class is used to compute value for a given key using the given mapping function, if key is not already associated with a value (or is mapped to null) and enter that computed value in Hashmap else null.


1 Answers

Use

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.

like image 81
4castle Avatar answered Sep 28 '22 03:09

4castle