VextoR
VextoR

Reputation: 5165

How to remove from a HashMap if value is present in Java 8 style

There is a Map<String, List<String>>. I want to delete a value from the List if the Map contains a key.

But is there a way to do it in Java 8 style? Like maybe using compute, merge or some other new method?

The code to remove element from the List in old style way:

public class TestClass {


    public static void main(String[] args) {
        Map<String, List<String>> map = new HashMap<>();
        map.put("key1", getList());
        map.put("key2", getList());

        //remove
        if (map.containsKey("key1")) {
            map.get("key1").remove("a2");
        }
        System.out.println(map);
    }

    public static List<String> getList(){
        List<String> arr = new ArrayList<String>();
        arr.add("a1");
        arr.add("a2");
        arr.add("a3");
        arr.add("a4");

        return arr;
    }   
}

Upvotes: 7

Views: 15164

Answers (2)

Anonymous
Anonymous

Reputation: 86272

We don’t have to Java-8-ify everything. Your code is fine as it stands. However, if you wish, Karol’s suggestion is fine, and here’s another one:

    Optional.ofNullable(map.get("key1")).ifPresent(v -> v.remove("a2"));

Opinions differ as to whether this is the wrong use of Optional. It’s certainly not its primarily intended use, but I find it acceptable.

Upvotes: 6

Karol Dowbecki
Karol Dowbecki

Reputation: 44952

You could use Map.computeIfPresent() but the improvement is questionable:

map.computeIfPresent("key1", (k, v) -> { v.remove("a2"); return v; });

Upvotes: 10

Related Questions