java 在哈希图上使用 removeif

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37161318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:15:46  来源:igfitidea点击:

Using removeif on a hashmap

javahashmap

提问by UsefulUserName

I am trying to remove entries from a Hashmap, if i have already used them. Sadly, I'm not familier with Java 8 lambda expressions, so I'm not sure how to remove the entries correctly. Could somebody help me or explain what I have to do?

如果我已经使用过它们,我正在尝试从 Hashmap 中删除它们。遗憾的是,我不熟悉 Java 8 lambda 表达式,所以我不确定如何正确删除条目。有人可以帮助我或解释我必须做什么吗?

Here is the way I've tried doing it:

这是我尝试过的方法:

ArrayList<Integer> range10 = new ArrayList<Integer>();
    ArrayList<Integer> range15 = new ArrayList<Integer>();
    ArrayList<Integer> rangeMax = new ArrayList<Integer>();

for (int age = 16; age <= 100; age++){
        for (Entry<Integer, Partner> entry : dbMap.entrySet()){
            int key = entry.getKey();
            Partner person = entry.getValue();
            if (person.getAge() == alter && person.getAgeRange() == 10){
                range10.add(key);
                entry.setValue(null);
            }
            else if (person.getAge() == alter && person.getAgeRange() == 15){
                range15.add(key);
                entry.setValue(null);
                }
            else if (person.getAge() == age){
                rangeMax.add(key);
                entry.setValue(null);
                }
            dbMap.entrySet().removeIf(entries->entries.getValue().equals(null));

        }

And I get a java.lang.NullPointerExceptionfor it. I don't think this is a duplicate to asking what a NullPointerexception is, since I'm primarily asking how to use the removeif-function.

我得到了java.lang.NullPointerException它。我不认为这与询问 NullPointerexception 是什么重复,因为我主要询问如何使用 removeif 函数。

回答by Adnan Isajbegovic

You get that because you call .equals() on getValue() object, which is null, so it will not work. That happens here:

你得到它是因为你在 getValue() 对象上调用了 .equals() ,它是null,所以它不会工作。这发生在这里:

dbMap.entrySet().removeIf(entries->entries.getValue().equals(null));

What you have to do is this:

你需要做的是:

dbMap.entrySet().removeIf(entries->entries.getValue() == null);