Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }   
}
like image 867
VextoR Avatar asked Dec 08 '22 12:12

VextoR


1 Answers

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

map.computeIfPresent("key1", (k, v) -> { v.remove("a2"); return v; });
like image 166
Karol Dowbecki Avatar answered Jan 29 '23 11:01

Karol Dowbecki