简体   繁体   English

如果Java 8样式中存在值,如何从HashMap中删除

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

There is a Map<String, List<String>> . 有一个Map<String, List<String>> I want to delete a value from the List if the Map contains a key. 如果Map包含键,我想从List删除一个值。

But is there a way to do it in Java 8 style? 但有没有办法用Java 8风格做到这一点? Like maybe using compute, merge or some other new method? 就像使用计算,合并或其他一些新方法?

The code to remove element from the List in old style way: 以旧样式方式从List中删除元素的代码:

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. 我们没有Java-8-ify的一切。 Your code is fine as it stands. 你的代码很好。 However, if you wish, Karol's suggestion is fine, and here's another one: 但是,如果你愿意,Karol的建议很好,这是另一个:

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

Opinions differ as to whether this is the wrong use of Optional . 关于这是否是对Optional的错误使用,意见不一。 It's certainly not its primarily intended use, but I find it acceptable. 它当然不是它的主要用途,但我觉得它是可以接受的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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