简体   繁体   中英

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;
    }   
}

你可以使用Map.computeIfPresent()但改进是有问题的:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM